Is there a way to check if something is an object ...
# announcements
s
Is there a way to check if something is an object vs. a class? For example, how could I create this if statement?
Copy code
sealed 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 */
    }
}
m
on JVM, you can do
Copy code
val isObject = item::class.objectInstance != null
s
Thanks, that helps for JVM. How about JS, native? I'm hoping to use this in multiplatform.
a
Copy code
if(item is Fruit.Orange) // . . .
s
I wish it was that simple. Unfortunately this is an oversimplified version. My use case is in a multiplatform library and I am dealing with generics.
l
aren’t they all objects?
Fruit.Apple("red")
also creates an instance
a
I think I do not understand your use case then
k
the
is
keyword checks to see type. For sealed classes that deal with both objects and classes you can do
Copy code
when (item) {
  is Apple -> ...
  Orange -> ...
}
This is because there's only ever a single instance of Orange, so the when statement uses referential equality.