Reputation: 949
I am really new to Kotlin. I want to implement something like this:
class classA {
fun doSomething(f: class){
when (f){
classB -> print("class B")
classC -> print("class C")
}
}
I don't have any idea on how to proceed. Should I use generics? Or anything else? Feel free to mark as duplicate if answer is already present.
Upvotes: 1
Views: 119
Reputation: 170745
You can write
fun doSomething(f: KClass<*>) {
when (f){
B::class -> print("class B")
C::class -> print("class C")
}
}
and then call it as doSomething(B::class)
or doSomething(String::class)
.
Many libraries will use Class
instead of KClass
, in which case you need B::class.java
.
See Class References documentation.
Upvotes: 1