Narrowing the type of an object reference, in order for even allowing variables to also have more than one type

In Ceylon, an

if (is Nil|File fileResource) {
   ...
}

construct, or like this:

Object obj = … ;
if (is Hello obj) {
obj.say();
}

by narrowing the type of an object reference simply like this, we can very expressively narrow an object type reference in an easily readable manner.

What (could) be the Kotlin’s equivalent of a syntax like this, which’d then even be used as a better syntax even for union types too, to allow a variable to have more than one type. Like:

shared void integerOrString(Integer|String input) {
    if (is Integer input) {
        print("Got the integer ``input``");
    } else {
        print("Got the string '``input``'");
    }
}

Maybe I miss something in your post, but what about:

if (obj is Hello) {

?

1 Like

Yes, thanks for that, but also:

How, and can we have one function with’d accept multiple types (like integers and strings) as valid in Kotlin?

No, currently union types are not supported. You would need to create some kind of a wrapper class.

1 Like

Overloading is an option.

1 Like

Hm… interesting. Do you think this is something that they’d possibly consider in the future…?