SayantanRC
SayantanRC

Reputation: 949

What is the best way to pass Class reference as a method parameter?

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

Answers (1)

Alexey Romanov
Alexey Romanov

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

Related Questions