Recall & Review
beginner
What is type inference in Kotlin?
Type inference is when the Kotlin compiler automatically figures out the type of a variable or expression without you having to explicitly write it.
Click to reveal answer
beginner
How does Kotlin infer the type of
val number = 10?Kotlin sees the value 10 is an integer, so it infers the type of
number as Int.Click to reveal answer
beginner
Can Kotlin infer the type of a variable declared with
var?Yes, Kotlin can infer the type for
var variables just like val, based on the assigned value.Click to reveal answer
intermediate
What happens if you declare a variable without initializing it, like
val x?Kotlin requires you to initialize variables when declaring them without an explicit type. Otherwise, the compiler cannot infer the type and will show an error.
Click to reveal answer
beginner
Why is type inference helpful for Kotlin programmers?
Type inference makes code shorter and easier to read by removing the need to write types explicitly when they are obvious from the assigned value.
Click to reveal answer
What type does Kotlin infer for
val name = "Alice"?✗ Incorrect
The value "Alice" is a text string, so Kotlin infers the type as String.
Which of these declarations will cause a type inference error in Kotlin?
✗ Incorrect
Declaring
val z without initialization or explicit type causes an error because Kotlin cannot infer the type.If you write
var count = 10, what type does Kotlin assign to count?✗ Incorrect
The number 10 is an integer, so Kotlin infers the type Int.
Can Kotlin infer the type of a variable from a function return value?
✗ Incorrect
Kotlin can infer the type of a variable from the return value of a function.
What keyword is used to declare a read-only variable with inferred type in Kotlin?
✗ Incorrect
val declares a read-only variable with type inferred by the compiler.Explain how Kotlin's compiler infers the type of a variable when you assign a value.
Think about how Kotlin guesses the type from the value you give.
You got /3 concepts.
Describe a situation where Kotlin's type inference will cause a compilation error.
What if you declare a variable but don't assign a value or type?
You got /3 concepts.