WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 13 of 100

What are smart casts in Kotlin, and how do they work?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, smart casts are a type of feature that allows the compiler to automatically cast an object to a more specific type, based on the evaluation of certain conditions. Essentially, this allows us to write more concise and readable code, without sacrificing on type-safety.

To understand how smart casts work, let’s consider the following code:

fun printLength(obj: Any) {
    if (obj is String) {
        println("Length of string: ${obj.length}")
    }
}

In this code, we have a function ‘printLength‘ that takes an object ‘obj‘ of type ‘Any‘ as an argument. Inside the function, we use an ‘if‘ statement with the ‘is‘ keyword to check whether ‘obj‘ is an instance of ‘String‘. If ‘obj‘ is indeed a string, then we can safely assume that it has a ‘length‘ property, and we use this property to print the length of the string.

Now, you may wonder: how does the compiler know that ‘obj‘ is indeed a ‘String‘ inside the ‘if‘ block? After all, the type of ‘obj‘ is still ‘Any‘, and we haven’t explicitly cast it to a ‘String‘.

This is where smart casts come into play. When the compiler encounters the ‘is‘ keyword inside the ‘if‘ statement, it evaluates the condition to check whether ‘obj‘ is an instance of ‘String‘. If the condition is true, the compiler automatically casts ‘obj‘ to a ‘String‘ inside the ‘if‘ block. This means that we can safely access the ‘length‘ property of ‘obj‘, without worrying about runtime errors.

Smart casts are not limited to just ‘if‘ statements; they can also be used with ‘when‘ expressions, as well as with ‘try-catch‘ blocks. For example:

fun printLength(obj: Any) {
    when (obj) {
        is String -> println("Length of string: ${obj.length}")
        is Int -> println("Square of integer: ${obj * obj}")
    }
    
    try {
        val str = obj as String
        println("Length of string: ${str.length}")
    } catch (e: Exception) {
        println("Not a string")
    }
}

In this updated code, we use a ‘when‘ expression to check the type of ‘obj‘, and print either the length of the string or the square of the integer. We also use a ‘try-catch‘ block to explicitly cast ‘obj‘ to a ‘String‘ and print its length; if the cast fails (i.e., if ‘obj‘ is not a string), then we catch the exception and print a message.

Overall, smart casts provide a powerful and concise way to work with type hierarchies in Kotlin, without sacrificing on type-safety. By allowing the compiler to perform automatic casts based on conditions, we can write more readable and expressive code, with fewer runtime errors.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics