Gavin
Gavin

Reputation: 1767

In Kotlin how do I groupBy type

I would like to group a list by the subtypes of its generic type argument.

That is a have a list with three types of objects all are a subtype of some type A.

The closest I can get is it.javaClass.typeName or it.javaClass.kotlin

The former creates keys of Strings which isn't ideal, but I can deal with. The later creates keys of KClassImpl which I can't actually import let alone create an instance of.

How do you groupBy type, then access the different keys in the resulting map?

Thanks.

Upvotes: 3

Views: 9361

Answers (1)

kocka
kocka

Reputation: 727

You can refer to kotlin class instances as Foo::class

data class Person(
    val firstName : String,
    val lastName : String
)

data class City(
    val name : String,
    val population: Int
)


fun main(args: Array<String>) {

    val list = listOf(
        Person("John", "Doe"),
        Person("Eugene", "Cuckoo"),
        City("London", 8500000),
        City("Berlin", 3500000),
        City("Hötyökmáró", 2)
    )

    val grouped = list.groupBy { it.javaClass.kotlin }

    println("Persons: ${grouped[Person::class]}")
    println("Cities: ${grouped[City::class]}")

}

Upvotes: 14

Related Questions