0
0
Kotlinprogramming~5 mins

Properties with val and var in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the difference between val and var in Kotlin properties?
val declares a read-only property (like a constant). You cannot change its value after initialization. var declares a mutable property, which means you can change its value later.
Click to reveal answer
beginner
Can a val property be assigned a value after the object is created?
No. A val property must be assigned once during initialization and cannot be reassigned later.
Click to reveal answer
beginner
How do you declare a mutable property named age of type Int in Kotlin?
You declare it using var age: Int. This means you can change the value of age anytime.
Click to reveal answer
beginner
What happens if you try to reassign a val property in Kotlin?
The compiler will give an error because val properties are read-only and cannot be reassigned after initialization.
Click to reveal answer
beginner
Example: What will this code print?<br>
val name = "Anna"
// name = "Bob" // What if uncommented?
The code will print nothing because it only declares name. If you uncomment the reassignment, the compiler will show an error because name is a val and cannot be changed.
Click to reveal answer
Which keyword declares a property that can be changed after initialization?
Avar
Bval
Cconst
Dlet
What happens if you try to assign a new value to a val property?
AIt works fine
BValue silently changes
CRuntime error
DCompiler error
How do you declare a read-only property in Kotlin?
Aval
Bvar
Clet
Dconst
Which of these is true about var properties?
AThey cannot be changed after initialization
BThey must be initialized with a value
CThey can be reassigned any number of times
DThey are constants
If you want a property that never changes after creation, which keyword do you use?
Avar
Bval
Cmutable
Dfinal
Explain the difference between val and var properties in Kotlin with examples.
Think about constants versus variables in everyday life.
You got /5 concepts.
    What error do you get if you try to change a val property after it is set? Why does Kotlin enforce this?
    Consider why some things in life should not change once set.
    You got /4 concepts.