CodeBlanks Logo Icon CodeBlanks

Properties

Learn to declare properties in a class.

Properties: val and var

A class's properties are declared with val or var. val is immutable, var is mutable.

class Box {
    val capacity: Int = 10
    var item: String = "empty"
}

val b = Box()
b.item = "pen"  // ok
// b.capacity = 20  // compile error

A val property is set once; it cannot change. A var property can be changed any time. Kotlin generates a getter (and a setter for var) automatically.

Automatic getters and setters

Kotlin generates a getter for every property behind the scenes; for var it also generates a setter. You do not write them explicitly; it is handled for you.

class Person(var name: String)

val p = Person("Alex")
println(p.name)  // getter called
p.name = "Ayşe"  // setter called

p.name actually calls getName(). This concise syntax creates a full getter/setter pair behind the scenes. Later you will see how to customise them.

Practice Add an item property to Box

Define class Box(var item: String). In main create val b = Box("pen"); change the property with b.item = "notebook"; print b.item.

Starter code

Main.kt
fun main() {
    // Define a Box class with a mutable item property
    // Create an instance, change item, print the result
}

Sample solution

Main.kt
class Box(var item: String)

fun main() {
    val b = Box("pen")
    b.item = "notebook"
    println(b.item)
}

Expected output

defter

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match keyword to meaning

Term Meaning
val Immutable
var Mutable
getter Reading
setter Writing

2 Fill in the blank: declare with var

Question
class Box {
    ____ item: String = ""
}
Answer
class Box {
    var item: String = ""
}

Explanation: var item is a mutable property.

3 What is the difference between val and var?

  • val is immutable, var is mutable Correct answer
  • val is mutable, var is immutable
  • they are the same
  • val does not exist

Explanation: val is set once, var can change later.

4 Fill in the blank: assign to the property

Question
val b = Box()
b.____ = "pen"
Answer
val b = Box()
b.item = "pen"

Explanation: b.item = "pen" changes the var property.

All lessons in Beginner