En la clase Kotlin, tengo parámetro de método como objeto (véase el documento Kotlin aquí ) para el tipo de clase T . Como objeto, paso diferentes clases cuando llamo al método. En Java podemos comparar la clase usando el instanceofobjeto de qué clase es.
Entonces, quiero verificar y comparar en tiempo de ejecución qué clase es.
¿Cómo puedo consultar la instanceofclase en kotlin?
kotlin
kotlin-extension
pRaNaY
fuente
fuente

Podemos verificar si un objeto se ajusta a un tipo dado en tiempo de ejecución usando el
isoperador o su forma negada!is.Ejemplo:
if (obj is String) { print(obj.length) } if (obj !is String) { print("Not a String") }Otro ejemplo en el caso de un objeto personalizado:
Vamos, tengo un
objtipoCustomObject.if (obj is CustomObject) { print("obj is of type CustomObject") } if (obj !is CustomObject) { print("obj is not of type CustomObject") }fuente
if,objse lanza automáticamente aString. Así que usted puede utilizar las propiedades tales comolengthdirectamente, sin la necesidad de convertir explícitamenteobjalStringinterior del bloque.Puede utilizar
is:class B val a: A = A() if (a is A) { /* do something */ } when (a) { someValue -> { /* do something */ } is B -> { /* do something */ } else -> { /* do something */ } }fuente
Intente usar la palabra clave llamada
isReferencia de página oficialif (obj is String) { // obj is a String } if (obj !is String) { // // obj is not a String }fuente
Puedes comprobar así
private var mActivity : Activity? = nullentonces
override fun onAttach(context: Context?) { super.onAttach(context) if (context is MainActivity){ mActivity = context } }fuente
Puede leer la documentación de Kotlin aquí https://kotlinlang.org/docs/reference/typecasts.html . Podemos verificar si un objeto se ajusta a un tipo dado en tiempo de ejecución usando el
isoperador o su forma negada!is, por ejemplo usandois:fun <T> 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 }luego, en la función principal, trato de imprimir y mostrarlo en la terminal:
fun main() { val stringResult = getResult("Kotlin") val intResult = getResult(100) // TODO 2 println(stringResult) println(intResult) }Esta es la salida
6 500fuente
Otra solución: KOTLIN
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if (fragment?.tag == "MyFragment") {}fuente