Start learning free

LESSON 183 OF 348 · OBJECT-ORIENTED PROGRAMMING

Class Fields in Kotlin: Properties with var and val

Lesson Read the full explanation

TL ; DR:

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


  • Declare a field with a type and a name, with public in front 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
}
  • public means "any code can read and write this field". 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.


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

If you don't assign a field, Kotlin fills it in for you:

  • Numbers default to 0

  • Boolean defaults to false

  • References (String, arrays, other classes) default to null


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

    KOTLIN · OBJECT-ORIENTED PROGRAMMING

    Class Fields in Kotlin, explained

    What a field is

    An empty Dog class makes every dog identical. To give each object its own data you attach fields to the class: variables that belong to it. Every object created from the class gets its own copy of each one, so two dogs can have different names without interfering with each other.

    In Kotlin a field declared in a class is a property. The compiler also generates a getter, and for var a setter, that outside code uses when it reads or writes the property with a dot.

    Declaring properties

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    
    • var declares a property that can be reassigned. val declares one that is assigned once and then read-only.
    • The type follows the name after a colon: name: String.
    • Properties are visible to any code by default. public is the default and is normally left out. A later lesson covers private.

    Every property needs a starting value

    Here Kotlin differs from languages that fill in zeros and nulls for you. A property in a class body must be initialized when it is declared, or in the constructor. This does not compile:

    class Dog {
        var age: Int
    }
    

    The compiler reports property must be initialized or be abstract. So there is no automatic 0 for numbers, false for booleans or null for references. If you want a missing value, say so in the type:

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

    The ? makes nickname nullable, so null is allowed. A plain String can never be null. For a property that you will assign later but cannot initialize now, lateinit var owner: String skips the initial value. Reading it before assigning throws an UninitializedPropertyAccessException with the message lateinit property owner has not been initialized.

    That is why the lesson's step gives each property a default value. It lets Dog() build a dog with no arguments.

    Reading and writing

    The dot operator reaches a property of one particular object:

    val dog = Dog()
    dog.name = "Rex"
    dog.age = 4
    println(dog.name)
    

    The last line prints Rex. Writing dog.age += 1 changes only this dog's age. If you create a second Dog, its name is still "" and its age still 0.

    A val property can be read but not assigned. With val species: String = "dog" in the class, d.species = "cat" fails with 'val' cannot be reassigned. Note that val dog = Dog() in the example above is a val variable holding a reference; it is the properties, which are var, that change.

    Computed properties

    A property does not have to store a value. It can have a getter that computes one each time it is read:

    class Dog {
        var name: String = ""
        var age: Int = 0
        val isPuppy: Boolean
            get() = age < 2
    }
    

    Here isPuppy has no storage of its own. With age set to 1 it reads as true, and after age is set to 5 it reads as false. From the outside it looks like any other property, which is why Kotlin code rarely needs separate getter methods.

    The exercise

    The starter code has an empty Dog and a mainFunction that prints ${dog.name} is ${dog.age} years old. The ${...} parts are string templates that insert values into the text. The code does not compile because Dog has no name or age. Step 1 declares both properties with var and a default value. Step 2 sets them through the dot operator before the print:

    class Dog {
        var name: String = ""
        var age: Int = 0
    }
    
    class Solution {
        fun mainFunction() {
            val dog = Dog()
            dog.name = "Rex"
            dog.age = 4
            println("${dog.name} is ${dog.age} years old")
        }
    }
    

    The output is Rex is 4 years old.

    Common mistakes

    • Omitting the initial value. var name: String in a class body does not compile.
    • Using val and then assigning. A val property cannot be changed from mainFunction.
    • Mismatched types. dog.name = 5 is rejected because a String property cannot hold an Int.
    • Misspelled property names. dog.nme = "Rex" fails with unresolved reference 'nme'.
    • Setting the property on the class. Properties belong to objects, so write dog.name, not Dog.name.

    Key takeaways

    • A field is a property: a variable declared in a class, with its own copy in every object.
    • Use var when the value can change and val when it cannot.
    • Kotlin gives no automatic defaults: initialize every property, make it nullable, or use lateinit.
    • Read and write properties with the dot operator.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free