Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading