0
0
Kotlinprogramming~5 mins

Type inference by the compiler in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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"?
AInt
BString
CBoolean
DAny
Which of these declarations will cause a type inference error in Kotlin?
Aval x = 5
Bvar y = true
Cval message = "Hi"
Dval z
If you write var count = 10, what type does Kotlin assign to count?
ADouble
BString
CInt
DFloat
Can Kotlin infer the type of a variable from a function return value?
AYes, if the function returns a value
BNo, you must always specify the type
COnly for built-in functions
DOnly if the function is inline
What keyword is used to declare a read-only variable with inferred type in Kotlin?
Aval
Bvar
Clet
Dconst
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.