How to check “instanceof ” class in kotlin?

后端 未结 8 1578
有刺的猬
有刺的猬 2020-12-14 05:14

In kotlin class, I have method parameter as object (See kotlin doc here ) for class type T. As object I am passing different classes when I am calling metho

8条回答
  •  天命终不由人
    2020-12-14 05:50

    You can read Kotlin Documentation here https://kotlinlang.org/docs/reference/typecasts.html . We can check whether an object conforms to a given type at runtime by using the is operator or its negated form !is, for the example using is:

    fun  getResult(args: T): Int {
        if (args is String){ //check if argumen is String
            return args.toString().length
        }else if (args is Int){ //check if argumen is int
            return args.hashCode().times(5)
        }
        return 0
    }
    

    then in main function i try to print and show it on terminal :

    fun main() {
        val stringResult = getResult("Kotlin")
        val intResult = getResult(100)
    
        // TODO 2
        println(stringResult)
        println(intResult)
    }
    

    This is the output

    6
    500
    

提交回复
热议问题