'If val variables are immutable how I was able to change its value?

class Mobile(val company: String= "unknown", var model: String ="unknown") {
fun call(mobile: Mobile) = "Calling with ${mobile.model} from the company ${mobile.company}"
}

fun main()
{
    val mobile = Mobile("Samsung", "S10")
}

In the previous code: How kotlin compiler was able to change the variable company although it was declared as 'val'?



Solution 1:[1]

Those values passed in the Mobile class are just default values as part of the declaration of the constructor of your Mobile class, those will be used if you don't provide any when instantiating the class. But since in you main you are instantiating the class with company="Samsung" and model="S10" those values are used instead of the defaults.

Keep in mind that class Mobile(val company: String= "unknown", var model: String ="unknown") is just a declaration so company and model are not really initialised until you call the constructor

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alain Plana