pozklundw
pozklundw

Reputation: 525

How to pass kotlin class or kotlin class instance as arguments

see following code:

class Ex() {
    fun m(i: Object) {
    }
}

class Ex2() {
    fun m2() {
        Ex().m(this)
    }    
}

How to make Ex#m receive Ex2 instance, I now can pass this.javaClass as arguments, but it's too trouble, what is "this"'s Class

update

change fun m(i: Object) to fun m(i: Ex2) can fix current example, but I hope KotlinObjectClass to make Ex#m receive variable type argument

update use Any can fix "variable type" question, but I hope more exactly, I hope receive type only KotlinClassObjectInstance

Upvotes: 4

Views: 15285

Answers (2)

miensol
miensol

Reputation: 41678

You can make use of reified type parameters like so:

class Ex() {
    inline fun <reified T> m() {
        println(T::class)
    }
}

class Ex2() {
    fun m2() {
        Ex().m<Ex2>()
    }
}

Now Ex2().m2() will print class Ex2

Upvotes: 3

Eugene Krivenja
Eugene Krivenja

Reputation: 656

Is this what are you looking for?

interface MyKotlin
class Ex {
  fun m(i: MyKotlin) {
  }
}
class Ex2 : MyKotlin {
  fun m2() {
    Ex().m(this)
  }
}
class Ex3 : MyKotlin {
  fun m3() {
    Ex().m(this)
  }
}

Upvotes: 1

Related Questions