typeof kotlin
The typeof
keyword is not available in Kotlin. However, you can achieve similar functionality using the is
operator or the ::class.java
property.
To check the type of a variable or an object in Kotlin, you can use the is
operator. It allows you to check if an object belongs to a specific type or its subtypes. The is
operator returns true
if the object is an instance of the specified type, and false
otherwise. Here's an example:
val obj: Any = "Hello, World!"
if (obj is String) {
println("obj is a String")
} else {
println("obj is not a String")
}
In this example, obj
is checked if it is an instance of the String
type. If it is, the message "obj is a String" is printed; otherwise, the message "obj is not a String" is printed.
Alternatively, you can also use the ::class.java
property to get the runtime class of an object. This property returns a Class
object that represents the runtime class of the object. Here's an example:
val obj: Any = "Hello, World!"
val objClass = obj::class.java
println("The class of obj is: $objClass")
In this example, the objClass
variable stores the runtime class of obj
, which is java.lang.String
. The class name is then printed using the println
function.
These are the ways you can check the type of an object in Kotlin.