0
0
Kotlinprogramming~5 mins

Val for immutable references in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does val mean in Kotlin?

val declares a read-only (immutable) reference. Once assigned, you cannot change what it points to.

Click to reveal answer
beginner
Can you reassign a new value to a val variable in Kotlin?

No, you cannot reassign a new value to a val variable. It is immutable after initialization.

Click to reveal answer
beginner
How is val different from var in Kotlin?

val is immutable (cannot be reassigned), while var is mutable (can be reassigned).

Click to reveal answer
beginner
Example: What happens if you try to reassign a val variable?<br>
val x = 10
x = 20

This will cause a compile-time error because x is declared with val and cannot be reassigned.

Click to reveal answer
intermediate
Does val guarantee the object it points to is immutable?
<p>No, <code>val</code> only means the reference cannot change. The object itself can still be mutable if its class allows it.</p>
Click to reveal answer
What does val declare in Kotlin?
AA mutable reference
BA function
CAn immutable reference
DA class
Can you reassign a new value to a val variable after initialization?
ANo, never
BOnly inside functions
CYes, anytime
DOnly if it is a number
Which keyword allows reassignment in Kotlin?
Avar
Bval
Cconst
Dfun
If you declare val list = mutableListOf(1, 2, 3), can you add elements to list?
ANo, because list is immutable
BOnly if you reassign list
CNo, because val forbids any changes
DYes, because the object is mutable
What error occurs if you try to reassign a val variable?
ARuntime error
BCompile-time error
CNo error
DLogical error
Explain what val means in Kotlin and how it differs from var.
Think about whether you can change the variable after setting it.
You got /4 concepts.
    Describe a situation where using val is better than var.
    Consider when you want to protect data from accidental changes.
    You got /4 concepts.