I’m looking at at Kotlin code sample, and I’m seei...
# announcements
g
I’m looking at at Kotlin code sample, and I’m seeing
is
used with optional types, which I don’t quite get:
if( myvar is MyObject? )
. Seems to be valid syntax, but I don’t understand what the
?
is adding. Any thoughts?
l
The cast passes if
myvar
is
null
g
It’s not really a cast, it’s just an instance check — but … I guess. I’m not sure that’s a value add in this case.
Yeah, fine, I guess that’s why it’s valid syntax. The condition will be true if the variable is null, which lets you avoid
if( myvar == null || myvar is MyObject )
if that’s what you really want.
Although in the code i’m looking at, there’s no reason to be doing that, because the very next thing is to do a myvar?.let or a myvar?.doSomething() on both conditions.
h
It’s not really a cast, it’s just an instance check
... well, in kotlin, it is also a cast. After the check passes,
myvar
can be used as a
MyObject
(or actually a
MyObject?
) without any (extra) cast.
f
T?
is the union
T|Null
and asks if the variable is either
T
or
Null
, the answer is clear. It is not true that a
is
performs a cast automatically in-place. It's rather that the compiler inserts a cast after the condition if it boils down to one concrete type where the cast is valid. We can decompose it to something like the following:
Copy code
when (myvar) {
    is MyObject -> {
        val _myvar = myvar as MyObject
        _myvar.doSomething()
    }
    is Null -> {
        val _myvar = null
        doSomethingElse()
    }
}
Kotlin does not have real intersection or union types, that is why the
T?
is a hard coded special case in the language. You may want to check out https://ceylon-lang.org/documentation/1.3/tour/types/ for a JVM language with full support of intersection and union types.
k
Did you just advertise ceylon in the kotlin slack? 😄
f
Not intentional. 😄
h
It is not true that a
is
performs a cast automatically
... but I don't know any kotlin compiler taht doesn't do the cast automatically after the
is
, so for any reasoning about it, you may assume that is the case.
f
@hallvard what I did want to clarify is simply that
is
by itself does not perform the cast but rather is sugar. I didn't want to say that you were wrong because from a user's perspective the behavior is exactly the same.
h
Sure. You're right about that