Component - Variables (val, var) and null safety
This UI component shows how Kotlin variables work with val and var, and how null safety helps avoid errors by handling nullable values safely.
This UI component shows how Kotlin variables work with val and var, and how null safety helps avoid errors by handling nullable values safely.
Activity > LinearLayout > [TextView (Title), TextView (Variable Info), Button (Change Variable)]
val is used for read-only variables, meaning their value cannot change once assigned.var allows changing the value; const is not a Kotlin keyword for variables; let is from other languages like Swift or JavaScript.? after the type means the variable can hold null.null if no value is assigned yet.var count: Int? = 5 count = null println(count)
count is declared as nullable Int (Int?) and initially set to 5.count is assigned null, which is allowed for nullable types, so printing it outputs null.val message: String = null println(message)
message is declared as non-nullable String but assigned null, which is not allowed.String?.var is needed, and it must allow null, so type must be nullable with ?.val (immutable) and assigns null to non-nullable type (error). var data: Int? = null uses var and nullable type with null initial value (correct). val data: Int? = 0 uses val (immutable) but nullable type with 0 initial value (not changeable). var data: Int = null uses var but non-nullable type assigned null (error).Pass the test and this pattern moves unknown