https://kotlinlang.org logo
s

Sonu Sanjeev

08/08/2021, 4:07 AM
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

ephemient

08/08/2021, 4:20 AM
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

Sonu Sanjeev

08/08/2021, 4:24 AM
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

ephemient

08/08/2021, 4:25 AM
or changing state, for example
set(value) { field = value }
s

Sonu Sanjeev

08/08/2021, 4:26 AM
Here my aim was to just invert the boolean value using "set(value) = " style of setter
e

ephemient

08/08/2021, 4:26 AM
invert which boolean?
s

Sonu Sanjeev

08/08/2021, 4:26 AM
isRectangle = true
e

ephemient

08/08/2021, 4:27 AM
as in, you want the next
isRectangle get()
to return false? how could that work?
j

James Whitehead

08/08/2021, 4:27 AM
Sounds like it would be better as a constructor parameter
e

ephemient

08/08/2021, 4:28 AM
a getter for a computed property makes sense, but a setter… much rarer
j

James Whitehead

08/08/2021, 4:28 AM
Or use a method rather than a property
e

ephemient

08/08/2021, 4:29 AM
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

Sonu Sanjeev

08/08/2021, 4:31 AM
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

James Whitehead

08/08/2021, 4:36 AM
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

ephemient

08/08/2021, 4:37 AM
yes. make it a
val
(only getter) instead of throwing an exception in the setter.
👍 1
s

Sonu Sanjeev

08/08/2021, 4:40 AM
Thank you @ephemient @James Whitehead. I was just trying to understand how and when to use different styles of property setters in kotlin.
2 Views