Bird
Raised Fist0
Kotlinprogramming~20 mins

Smart casts in when and if in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Smart Casts Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of smart cast in if condition
What is the output of this Kotlin code using smart casts in an if statement?
Kotlin
fun main() {
    val obj: Any = "Hello"
    if (obj is String) {
        println(obj.length)
    } else {
        println("Not a string")
    }
}
A5
BNot a string
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
The variable obj is checked to be a String before accessing length.
❓ Predict Output
intermediate
2:00remaining
Smart cast behavior in when expression
What will be printed by this Kotlin code using smart casts in a when expression?
Kotlin
fun main() {
    val x: Any = 42
    when (x) {
        is String -> println("String of length ${x.length}")
        is Int -> println("Int doubled is ${x * 2}")
        else -> println("Unknown type")
    }
}
ACompilation error
BInt doubled is 84
CUnknown type
DString of length 2
Attempts:
2 left
💡 Hint
Check the type of x and how smart casts work in when branches.
🔧 Debug
advanced
2:00remaining
Why does this smart cast fail?
Consider this Kotlin code snippet. Why does it fail to compile?
Kotlin
fun main() {
    var obj: Any? = "Kotlin"
    if (obj is String && obj.length > 3) {
        println(obj.length)
    }
}
ABecause length property is not accessible on String
BBecause obj is not declared as val
CBecause && operator cannot be used with smart casts
DBecause obj is nullable, smart cast is not possible without explicit null check
Attempts:
2 left
💡 Hint
Think about nullability and smart casts combined with logical operators.
📝 Syntax
advanced
2:00remaining
Identify the syntax error with smart casts in when
Which option contains a syntax error related to smart casts in this Kotlin when expression?
Kotlin
fun main() {
    val y: Any = 10
    when (y) {
        is String -> println(y.length)
        is Int -> println(y + 5)
        else -> println("Unknown")
    }
}
AReplacing 'else -> println("Unknown")' with 'else println("Unknown")'
BReplacing 'is String -> println(y.length)' with 'is String -> println(y.toUpperCase())'
CReplacing 'when (y)' with 'when y'
DReplacing 'is Int -> println(y + 5)' with 'is Int -> println(y.length)'
Attempts:
2 left
💡 Hint
Check the syntax of when branches and the use of arrows.
🚀 Application
expert
3:00remaining
Determine the number of items in the resulting map
What is the number of entries in the map produced by this Kotlin code using smart casts in when?
Kotlin
fun main() {
    val items: List<Any> = listOf("apple", 10, "banana", 3.14)
    val result = items.mapNotNull {
        when (it) {
            is String -> it.uppercase()
            is Int -> (it * 2).toString()
            else -> null
        }
    }.associateWith { it.length }
    println(result.size)
}
A2
B5
C3
D4
Attempts:
2 left
💡 Hint
Count how many items are transformed and not filtered out.

Practice

(1/5)
1. What does Kotlin's smart cast feature do inside an if or when block?
easy
A. Disables type checking inside the block
B. Requires explicit casting of variables after type checks
C. Automatically treats a variable as a specific type after a type check
D. Converts all variables to strings inside the block

Solution

  1. Step 1: Understand smart cast purpose

    Smart casts let Kotlin automatically treat a variable as a more specific type after you check its type.
  2. Step 2: Apply to if/when blocks

    Inside if or when, Kotlin knows the variable's type and lets you use it without manual casting.
  3. Final Answer:

    Automatically treats a variable as a specific type after a type check -> Option C
  4. Quick Check:

    Smart cast = automatic type use after check [OK]
Hint: Smart casts auto-change type after check in if/when [OK]
Common Mistakes:
  • Thinking manual cast is always needed
  • Assuming smart casts disable type checks
  • Believing variables convert to string automatically
2. Which of the following is the correct syntax to use smart casts in a when expression for variable obj?
easy
A. when obj { is String -> println(obj.length) else -> println("Not a string") }
B. when (obj) { obj is String -> println(obj.length) else -> println("Not a string") }
C. when (obj) { String -> println(obj.length) else -> println("Not a string") }
D. when (obj) { is String -> println(obj.length) else -> println("Not a string") }

Solution

  1. Step 1: Check correct when syntax

    The when expression requires parentheses around the variable: when (obj).
  2. Step 2: Use type check correctly

    The correct type check is is String without repeating variable name inside the block.
  3. Final Answer:

    when (obj) { is String -> println(obj.length) else -> println("Not a string") } -> Option D
  4. Quick Check:

    Correct when syntax uses parentheses and is [OK]
Hint: Use parentheses and 'is' keyword in when [OK]
Common Mistakes:
  • Omitting parentheses around variable
  • Using variable name inside when branches
  • Using type name without 'is' keyword
3. What will be the output of this Kotlin code?
fun test(obj: Any) {
    when (obj) {
        is String -> println(obj.length)
        is Int -> println(obj + 1)
        else -> println("Unknown")
    }
}

test("Hello")
test(5)
test(3.14)
medium
A. 5 6 7
B. 5 6 Unknown
C. Hello 6 Unknown
D. 5 5 Unknown

Solution

  1. Step 1: Analyze each call

    For test("Hello"), obj is String, so prints length 5.
    For test(5), obj is Int, so prints 5 + 1 = 6.
    For test(3.14), no matching type, prints "Unknown".
  2. Step 2: Confirm output lines

    Outputs are:
    5
    6
    Unknown
  3. Final Answer:

    5 6 Unknown -> Option B
  4. Quick Check:

    Smart cast uses type to choose output [OK]
Hint: Match type in when to get output [OK]
Common Mistakes:
  • Confusing string length with string itself
  • Adding 1 to string instead of int
  • Expecting default else to print number
4. Identify the error in this Kotlin code using smart casts:
fun check(obj: Any) {
    if (obj is String) {
        println(obj.length)
    } else if (obj is Int) {
        println(obj + 1)
    } else {
        println(obj.length)
    }
}
medium
A. Trying to access length on obj in else block without type check
B. Missing parentheses in if condition
C. Using else if instead of when
D. Smart casts do not work inside if blocks

Solution

  1. Step 1: Review else block usage

    In the else block, obj can be any type, but code tries to access obj.length which is invalid for non-String types.
  2. Step 2: Understand smart cast limits

    Smart casts only apply after type checks. Here, no type check before accessing length in else block causes error.
  3. Final Answer:

    Trying to access length on obj in else block without type check -> Option A
  4. Quick Check:

    Access property only after type check [OK]
Hint: Check type before accessing properties [OK]
Common Mistakes:
  • Assuming else block has smart cast automatically
  • Confusing else if with when
  • Thinking smart casts fail inside if blocks
5. Given a list of Any objects, write a Kotlin function using when with smart casts to return a list of strings describing each element's type and value. What is the correct implementation?
fun describeList(items: List<Any>): List<String> {
    return items.map { item ->
        when (item) {
            is String -> "String of length ${'$'}{item.length}"
            is Int -> "Int with value ${'$'}item"
            else -> "Unknown type"
        }
    }
}
hard
A. Correct as is, smart casts allow using item.length and item directly
B. Needs explicit casts like (item as String).length and (item as Int)
C. Cannot use smart casts inside lambda expressions
D. Must use if-else instead of when for smart casts

Solution

  1. Step 1: Check smart cast usage in when

    The when expression smart casts item to String or Int automatically after type check.
  2. Step 2: Confirm lambda and map usage

    Inside the lambda, smart casts work normally, so accessing item.length and item is valid without explicit casts.
  3. Final Answer:

    Correct as is, smart casts allow using item.length and item directly -> Option A
  4. Quick Check:

    Smart casts work inside lambdas and when [OK]
Hint: Smart casts work inside lambdas and when blocks [OK]
Common Mistakes:
  • Adding unnecessary explicit casts
  • Thinking smart casts don't work in lambdas
  • Replacing when with if-else unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard