Home > database >  Why are func parameters immutable but constructor param can be mutable in kotlin?
Why are func parameters immutable but constructor param can be mutable in kotlin?

Time:08-26

I'm new to kotlin, I just realised that function parameters are immutable: https://blog.jetbrains.com/kotlin/2013/02/kotlin-m5-1/

We removed support for mutable parameters, as in

fun foo(var x: Int) {
  x = 5
}

However for class constructors, it can be mutable: https://kotlinlang.org/docs/classes.html#constructors

class Person(
    val firstName: String,
    val lastName: String,
    var age: Int, // trailing comma
) { /*...*/ }

Much like regular properties, properties declared in the primary constructor can be mutable (var) or read-only (val).

why? what's the use case of us having a mutable constructor parameters?

CodePudding user response:

Function parameter mutability is a frequent source of bugs in languages that allow it, so the Kotlin designers decided to disallow it.

In a primary constructor, the parameters that are preceded with val or var are not actually accessible because they are immediately converted into properties. You can have init blocks in your class, but they are working with the class properties, not the constructor's val/var parameters. Note, you can also define parameters in your constructor that are not properties, and these indeed are immutable in the init blocks.

When you define a var in a primary constructor, it is a class property.

  • Related