Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions src/checked-casts.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ Flix has two _safe_ upcast constructs:
The following program:

```flix
import java.lang.Object

def main(): Unit =
let s = "Hello World";
let o: ##java.lang.Object = s;
let _: Object = s;
()
```

Expand All @@ -27,33 +29,35 @@ does not compile:
```
❌ -- Type Error --------------------------------------------------

>> Expected type: 'Object' but found type: 'String'.
>> Unexpected type: expected 'java.lang.Object', found 'String'.

4 | let o: ##java.lang.Object = s;
^
expression has unexpected type.
5 | let _: Object = s;
^
expression has unexpected type.
```

because in Flix the `String` type is _not_ a subtype of `Object`.

We can use a checked type cast to safely upcast from `String` to `Object`:

```flix
import java.lang.Object;

def main(): Unit =
let s = "Hello World";
let o: ##java.lang.Object = checked_cast(s);
let _: Object = checked_cast(s);
()
```

We can use the `checked_cast` construct to safely upcast any Java type to one of
its super-types:

```flix
let _: ##java.lang.Object = checked_cast("Hello World");
let _: ##java.lang.CharSequence = checked_cast("Hello World");
let _: ##java.io.Serializable = checked_cast("Hello World");
let _: ##java.lang.Object = checked_cast(null);
let _: ##java.lang.String = checked_cast(null);
let _: Object = checked_cast("Hello World");
let _: CharSequence = checked_cast("Hello World");
let _: Serializable = checked_cast("Hello World");
let _: Object = checked_cast(null);
let _: String = checked_cast(null);
```

## Checked Effect Casts
Expand Down
6 changes: 3 additions & 3 deletions src/unchecked-casts.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Flix programmers should normally never need to use an unchecked type cast.
The expression below casts a `String` to an `Object`:

```flix
unchecked_cast("Hello World" as ##java.lang.Object)
unchecked_cast("Hello World" as Object)
```

Note: It is safer to use the `checked_cast` expression.
Expand All @@ -26,7 +26,7 @@ Note: It is safer to use the `checked_cast` expression.
The expression below casts the `null` value (of type `Null`) to `String`:

```flix
unchecked_cast(null as ##java.lang.String)
unchecked_cast(null as String)
```

Note: It is safer to use the `checked_cast` expression.
Expand All @@ -37,7 +37,7 @@ The expression below contains an illegal cast and triggers a
`ClassCastException` at runtime:

```flix
unchecked_cast((123, 456) as ##java.lang.Integer)
unchecked_cast((123, 456) as Integer)
```

## Effect Casts
Expand Down