Start learning free

LESSON 288 OF 677 · FUNCTIONS & CLASSES

Class Fields in Kotlin

Lesson

TL ; DR:

  • A field is a variable that lives inside a class. Each object of that class has its own copy.


  • Declare a field (Kotlin calls it a property) with var, a name, a type and an initial value. It is public by default, so other code can read and write it:

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    

  • Access a field on an object with the dot operator: dog.name = "Rex"



Full lesson:

Right now your Dog class is just an empty shell — every Dog object you create is identical to every other one. We need a way to attach data to each object.

That's what fields are for. A field is a variable that belongs to a class — and each object created from that class gets its own copy of every field.


Declaring fields

class Dog {
    var name: String = ""
    var age: Int = 0
}
  • Properties are public by default, which means "any code can read and write this field", so you don't write the keyword. You'll see private later for fields that should only be touched by the class itself.

  • var name: String = "" is just a variable declaration — same syntax you'd use anywhere else. Kotlin requires an initial value here, so each new Dog starts with an empty name and age 0.


Reading and writing fields

val dog = Dog()
dog.name = "Rex"        // write
dog.age = 4
println(dog.name)   // read → prints "Rex"

Each object has its own slot for every field, so two dogs can have different names without interfering.


Default values

Kotlin does not fill in a default for you: a property must be given an initial value where it is declared (or in a constructor). Common starting values are:

  • Numbers: 0

  • Boolean: false

  • String: "". A reference type can only hold null if you declare it nullable, such as String?


Your task

Update the Dog class to have two fields: name (a String) and age (an Int). Then in mainFunction, set them on the dog object so the pre-filled println prints:

Rex is 4 years old
STEP 1 OF 2
    Ctrl + Enter to check