Allow setter to return types other than unit?

When I’m using more complex setters, I sometimes find myself writing code like this:

class <T, R> myClass {
  var mVar: T
    private set

  fun setVar(value: T): R {
    mVar = value
    // do stuff
    val code: R = // relevent information about the stuff we just did
    return code
  }
}

This works, but we lose a lot of what’s nice about properties. This would be nicer:

class <T, R> myClass {
  var mVar: T
    // get is still type T
    set(value: T): R {
      field = value
      // do stuff
      val code: R = // relevent information about the stuff we just did
      return code
    }
}

Thoughts?

Sure?

val a =  myClass.mVar = b
assert ( a != b )

Or classic
if (a = b)

Assignments are not expressions in Kotlin, they are statements and is a GOOD thing. No thank you on reversing that.

Just want to note that allowing setters with non-unit return type isn’t the same as allowing assigment to be an expression.

For example we have Map.put member which return the previous value, and Map.set extension which allows to use assigment syntax. If non-unit setters were allowed it could be a single method, so that you call it a form of assigment if you don’t care about its return value, or in a form of function call if you do.

Yeah, the example that prompted this was a class that wraps a list, much like the map example. ArrayList returns some metadata when you perform operations, and I wanted to pass that on.

And, the want is mostly for code organization within the class – I like having getters and setters explicitly attached to properties – not outside it, where I don’t particularly like the val a = myClass.mVar = b syntax (but val a = myClass.mVar.set(b) is nice).

1 Like