dalexander
10/01/2019, 2:24 PM// both Foo and Bar extend Item
val item: Any? = getSomething()
if(item is Foo || item is Bar) {
// I would expect this to smart cast to Item -- defining Item as a sealed class doesn't seem to help either
doThingWithItem(item) //Error - Type mismatch, required: Item, found Any?
}
diesieben07
10/01/2019, 2:26 PMShawn
10/01/2019, 2:28 PMitem is Item
?dalexander
10/01/2019, 2:30 PMdoThingWithItem()
with any Item subclass (I'm actually going to check though-- this line came about during a Java -> Kotlin conversion).Ruckus
10/01/2019, 2:32 PMif(item is Foo || item is Bar)
is type checking. Do you mean you don't like casting if you can avoid it?dalexander
10/01/2019, 2:32 PMItems
that should be excluded from that call.diesieben07
10/01/2019, 2:32 PMItem
suddenly your smart-cast no longer compiles (even worse, it's in a seperately compiled library and is now incorrect!)gian
10/01/2019, 2:33 PMdalexander
10/01/2019, 2:33 PMItem
doesn't mean if something is a Foo
or Bar
that it is also no longer an Item
.diesieben07
10/01/2019, 2:34 PMdalexander
10/01/2019, 2:34 PMgian
10/01/2019, 2:34 PMabstract class Parent
class Child1 : Parent()
fun main() {
val a: Any? = ""
if (a is Child1)
funOnParent(a)
}
fun funOnParent(parent: Parent) = println(parent.javaClass)
This is working for medalexander
10/01/2019, 2:35 PMif(item is Foo) {
doThingWithItem(item)
}
it works by the way.diesieben07
10/01/2019, 2:35 PMFoo
.gian
10/01/2019, 2:36 PMItem
diesieben07
10/01/2019, 2:37 PMdalexander
10/01/2019, 2:37 PMKroppeb
10/01/2019, 3:48 PMif(item is Foo || item is Bar) {
doThingWithItem(item)
}
if(item is Foo) {
doThingWithItem(item)
} elseif(item is Bar){
doThingWithItem(item)
}
and
when(item) {
is Foo -> doThingWithItem(item)
is Bar -> doThingWithItem(item)
}
interface Item
class Foo:Item
class Bar:Item
fun getValue(): Any? = TODO()
fun main(){
// a:Any
val a = getValue().let{if(it is Foo || it is Bar) it else TODO()}
// b:Item
val b = when(val t = getValue()){
is Foo -> t
is Bar -> t
else -> TODO()
}
// c:Item
val c = getValue().let{if(it is Foo) it else (if(it is Bar) it else TODO())}
}
mikhail.zarechenskiy
10/01/2019, 4:09 PMFoo
and Bar
after a check like item is Foo || item is Bar
for item
can be a good approximation. I think it can be a nice feature, @dalexander can you please create a YT ticket?dalexander
10/01/2019, 4:16 PM