https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

John Guerra

09/20/2020, 4:59 PM
Would there be a better way of handling this?
Copy code
internal abstract val packetTypes: List<KClass<*>>
Cause there's times where it'd look like this:
Copy code
override val packetTypes = listOf(
    PacketPlayInFlying::class,
    PacketPlayInFlying.PacketPlayInPosition::class,
    PacketPlayInFlying.PacketPlayInPositionLook::class,
    PacketPlayInFlying.PacketPlayInLook::class
)
Which honestly isn't always very pretty to look at. If I only add
PacketPlayInFlying::class
to the list then the other classes won't be retrieved. I have to manually add each one so they can be detected.
c

Christopher Elías

09/20/2020, 9:23 PM
Uhm I don't know what are trying to do, but it seems like you wan't to have a list of subclasses of type PacketPlayInFlying, have you try to use sealed classes? https://kotlinlang.org/docs/reference/sealed-classes.html Also, can you give more details on what are you trying to achive?
m

Michael de Kaste

09/21/2020, 7:33 AM
like @Christopher Elías said, perhaps sealed subclasses is what you're after. However, since your example contains a class and nested classes, you can do this:
Copy code
PacketPlayInFlying::class.nestedClasses + PacketPlayInFlying::class
👍 1
another note is, that I dont know what you mean by "the other classes won't be retrieved". By what exactly? If you do a direct equality check, you will get none. But by checking for instance (with the 'is' operator), you'll get all
Copy code
sealed class Foo{
    data class Bar1(val string: String) : Foo()
    data class Bar2(val int: Int) : Foo()
}

val list: List<Any> = listOf(Foo.Bar1(""), Foo.Bar1(" "), Foo.Bar1("  "), Foo.Bar2(0), Foo.Bar2(1))

fun main(){
    list.filter { it::class == Foo::class }.forEach(::println) //Prints none
    list.filterIsInstance(Foo::class.java).forEach(::println) //Prints all
}
👍 1