Scott Whitman
12/10/2020, 7:18 PMsealed class Fruit {
class Apple(val color: String) : Fruit()
object Orange : Fruit()
}
fun main() {
val list = listOf(Fruit.Apple("red"), Fruit.Orange)
for (item in list) {
if (/* item is object? */) /* do something */
else /* do something else */
}
}
Milan Hruban
12/10/2020, 7:26 PMval isObject = item::class.objectInstance != null
Scott Whitman
12/10/2020, 7:31 PMandylamax
12/11/2020, 1:30 AMif(item is Fruit.Orange) // . . .
Scott Whitman
12/11/2020, 1:49 AMLammert Westerhoff
12/11/2020, 1:44 PMFruit.Apple("red")
also creates an instanceandylamax
12/11/2020, 10:34 PMkevin.cianfarini
12/14/2020, 4:46 PMis
keyword checks to see type. For sealed classes that deal with both objects and classes you can do
when (item) {
is Apple -> ...
Orange -> ...
}
This is because there's only ever a single instance of Orange, so the when statement uses referential equality.