The differences between Val and Var in Kotlin

0 min read 177 words

Among all the many keywords that Kotlin comes with, there exists val and var. What are they used for? What are the differences, and why would you use one over another?

They are both used to declare variables in Kotlin. But how are they different?

What is val?

val is used to declare a variable that is read-only, and who’s value does not change.

Note that this only applies to the parent variable, and not it’s properties. The properties of the variable are still mutable.

fun copyAddress(address: Address): Address {
    val result = Address() // result is read only
    result.name = address.name // but not their properties.
    result.street = address.street
    // ...
    return result
}

What is var?

Just like val, var is also used to declare a variable. However, its value can be mutable.

var is used to declare a variable that can be changed. It can also be assigned multiple times.

fun getName(address: Address): String {
    var result = "Name: " // result is mutable (can be changed)
    // ...
    return result + address.name
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts