geoffrey
03/22/2018, 5:06 PMis
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?louiscad
03/22/2018, 5:07 PMmyvar
is null
geoffrey
03/22/2018, 5:08 PMgeoffrey
03/22/2018, 5:10 PMif( myvar == null || myvar is MyObject )
if that’s what you really want.geoffrey
03/22/2018, 5:11 PMhallvard
03/22/2018, 5:17 PMIt’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.Fleshgrinder
03/22/2018, 5:38 PMT?
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:
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.karelpeeters
03/22/2018, 5:52 PMFleshgrinder
03/22/2018, 5:53 PMhallvard
03/23/2018, 7:47 AMIt is not true that aperforms a cast automaticallyis
hallvard
03/23/2018, 7:47 AMis
, so for any reasoning about it, you may assume that is the case.Fleshgrinder
03/23/2018, 4:06 PMis
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.hallvard
03/23/2018, 4:24 PM