Why. cant you have a custom setter on a constructo...
# language-evolution
s
Why. cant you have a custom setter on a constructor parameter? How can I make a property with a custom setter be required when instantiating a class?
Copy code
class Foo(
    var x: Int = 0
    var y: Int
        set(value) {
            field = value
            x += value
        }
)
l
You can only have custom getter setter on properties within the block. It's just a design choice.
a
you could move
y
to the class body, and pass in the initial value of
y
as a construction parameter
Copy code
class Foo(
    var x: Int = 0,
    y: Int, // initial value of y
) {
  var y: Int = y // set the initial value of y
    set(value) {
      field = value
      x += value
    }
}
a
What about data classes then ?
r
@Ayfri That's not possible. The reasoning is "that's not what data classes are for".
e
Exactly. Data classes are designed to be transparent wrappers over a group of related properties and must not do any custom processing on them.
a
Okay I see, thanks !
s
imo, you should try and keep your data classes to be immutable as much as possible non-immutable data classes lead to code smell
3