Avatar ·

How to check object type (instanceof) in Kotlin? Analog of Java instanceof

Hi! I just started learning Kotlin after Java and encountered a problem. In Java, I constantly used the instanceof operator to check if an object is an instance of a certain class. For example:

// Java
if (obj instanceof String) {
    String str = (String) obj;
    System.out.println(str.length());
}

But in Kotlin, I can't find a direct analog. I tried writing obj instanceof String, but the compiler gives an error. I tried using is — it seemed to work, but I'm not sure if it's correct.

Here's what I wrote:

fun checkType(obj: Any) {
    // Trying to check the type
    if (obj is String) {
        // Want to call the length() method
        println(obj.length)
    }
}