Hi, When I write code like this on a setter functi...
# announcements
s
Hi, When I write code like this on a setter function, I am getting the following error Type mismatch. "*Required: Unit, Found: Boolean*".
Copy code
var isRectangle: Boolean
        get() = field
        set(value) = value.not()  // The error is here
How is it possible to return a Unit type when we use a syntax like "set(value) = " . Thanks in Adavance
e
a setter function is expected to have side effects only, no return value (hence Unit)
what do you expect to happen when you evaluate
isRectangle = true
or
isRectangle = false
?
s
So is this type of syntax for setter only used for side effects?. I believe when you say side effect, it means something like throwing an exception on setter?
Copy code
set(value) = throw Exception("")
e
or changing state, for example
set(value) { field = value }
s
Here my aim was to just invert the boolean value using "set(value) = " style of setter
e
invert which boolean?
s
isRectangle = true
e
as in, you want the next
isRectangle get()
to return false? how could that work?
j
Sounds like it would be better as a constructor parameter
e
a getter for a computed property makes sense, but a setter… much rarer
j
Or use a method rather than a property
e
since `isRectangle`'s observed value is always based on
width
and
height
, do you expect setting it to somehow change
width
and
height
to "correct" the computed value of
isRectangle
?
s
My aim was to achieve the equivalent of
Copy code
set(value) {
    field = value.not()
}
using "set(value) = " style.
I have updated the get method to just return the field
@ephemient @James Whitehead my aim here is to simply understand when to use "set(value) = " style of setter functions.
The only usecase I can think for this style of assignment is this.
Copy code
set(value) = throw Exception("Cannot set value")
j
Personally I've not come across a real world use-case for such a thing. As an aside, rather than throwing an exception in your example, it is possible to simply declare the setter as private.
If the variable shouldn't be mutated at all, hence the need to throw an exception, you should just use
val
instead
☝️ 1
e
yes. make it a
val
(only getter) instead of throwing an exception in the setter.
👍 1
s
Thank you @ephemient @James Whitehead. I was just trying to understand how and when to use different styles of property setters in kotlin.