Skip to content

Commit 9109395

Browse files
authored
Update implicit casting example (#2370)
1 parent 581f7bf commit 9109395

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

_overviews/scala3-book/first-look-at-types.md

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -238,20 +238,19 @@ Value types can be cast in the following way:
238238
For example:
239239

240240
```scala
241-
val x: Long = 987654321
242-
val y: Float = x // 9.8765434E8 (note that some precision is lost in this case)
241+
val b: Byte = 127
242+
val i: Int = b // 127
243243

244244
val face: Char = '☺'
245245
val number: Int = face // 9786
246246
```
247247

248-
Casting is unidirectional.
249-
This will not compile:
248+
You can only cast to a type if there is no loss of information. Otherwise, you need to be explicit about the cast:
250249

251-
```
250+
```scala
252251
val x: Long = 987654321
253-
val y: Float = x // 9.8765434E8
254-
val z: Long = y // Does not conform
252+
val y: Float = x.toFloat // 9.8765434E8 (note that `.toFloat` is required because the cast results in percision loss)
253+
val z: Long = y // Error
255254
```
256255

257256
You can also cast a reference type to a subtype.

0 commit comments

Comments
 (0)