How to check generic type in Kotlin?

前端 未结 4 675
温柔的废话
温柔的废话 2020-12-29 21:47

I have class

class Generic()

and this code is\'t correct

fun typeCheck(s: SuperType): Unit {
               


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 22:18

    If you need to check if something is of generic type T you need to to have an instance of Class to check against. This is a common technique in Java however in Kotlin we can make use of an inlined factory method that gets us the class object.

    class Generic(val klass: Class) {
        companion object {
            inline operator fun invoke() = Generic(T::class.java)
        }
    
        fun checkType(t: Any) {
            when {
                klass.isAssignableFrom(t.javaClass) -> println("Correct type")
                else -> println("Wrong type")
           }
    
        }
    }
    
    fun main(vararg args: String) {
        Generic().checkType("foo")
        Generic().checkType(1)
    }
    

提交回复
热议问题