0
0
Kotlinprogramming~5 mins

Properties with val and var in Kotlin

Choose your learning style9 modes available
Introduction

Properties let you store information inside objects. Using val means the value cannot change, while var means it can change.

When you want to keep some information fixed and not allow changes, like a person's birth date.
When you want to allow updates to information, like a user's current score in a game.
When you want to clearly show which data should stay constant and which can be modified.
When you want to prevent accidental changes to important data by using <code>val</code>.
When you want to create simple data holders with readable and writable properties.
Syntax
Kotlin
class MyClass {
    val readOnlyProperty: Type = value  // cannot be changed
    var readWriteProperty: Type = value // can be changed
}

val means the property is read-only after initialization.

var means the property can be changed anytime.

Examples
name cannot be changed once set, but age can be updated.
Kotlin
class Person {
    val name: String = "Alice"
    var age: Int = 30
}
Accessing a val property just reads it. A var property can be assigned a new value.
Kotlin
val car = Car()
println(car.model) // read-only
car.speed = 100   // can change speed
Sample Program

This program shows a book with a fixed title and a pagesRead property that can change. It prints the title and pages read before and after updating.

Kotlin
class Book {
    val title: String = "Kotlin Basics"
    var pagesRead: Int = 0
}

fun main() {
    val myBook = Book()
    println("Title: ${myBook.title}")
    println("Pages read: ${myBook.pagesRead}")
    
    myBook.pagesRead = 50
    println("Pages read after update: ${myBook.pagesRead}")
    
    // myBook.title = "New Title" // This line would cause an error because title is val
}
OutputSuccess
Important Notes

Trying to change a val property after it is set will cause a compile error.

You can think of val as a constant property and var as a variable property.

Summary

val properties are read-only after initialization.

var properties can be changed anytime.

Use val to protect data from accidental changes.