Boolean extension function
Asked Answered
V

4

6

When I try to create Extension Function to set Boolean true or false like the below.

Boolean.setTrue(){
 this = true
}

Boolean.setFalse(){
 this = false
}

It says variable expected. How to achieve this.

Vitiate answered 29/8, 2017 at 19:3 Comment(9)
In what Situation do you need this?Kendre
to make the code more readable.Vitiate
It can't be more readable than myBool = falseKendre
Generally you would be making the code less readable by not following the usual conventions. Either way it doesn't matter since you can't ever change the value of this, extension function or not.Jerrybuilt
compare to !someBoolean, someBoolean.not() looks readable right. That the way I tried this. But now I underStood the concept.Vitiate
To add, if you could redefine this you could use that to make a constructor possibly return not an instance of the class it is the constructor for, which would really confuse code (in plain Java if you could do that you could even make a constructor which returns null, which would really break a lot of normally safe assumptions)Mahlstick
that makes sense. Thank youVitiate
Related: #7980123Milch
Hey guys, Bhuvanesh asked something that is totally feasible in C#, Swift...Plater
M
6

You cannot change the value of this, this would break a lot of assumptions, even if you could you would not be able to change the value, as Booleans are immutable.

More generally, there is a fine line between simplifying code, and making it more complex, and in this case that would complicate it. I would agree that adding String.splitByDot() may make sense, but replacing idiomatic code tends to just make the code more complex, as you start to wonder why the code had to be replaced.

Mahlstick answered 29/8, 2017 at 19:23 Comment(0)
K
3

Sorry but this does not make sense. Just use myBool=false, it's what anyone understands and cannot get any more readable. Also Boolean is immutable and what you're trying isn't possible anyways.

We have to be careful not to overuse extensions. It's one of the greatest features Kotlin (and others) offers, but in certain examples, e.g. trying to change the way a dead simple Boolean is being assigned, it's getting dangerous IMHO (luckily it's not possible).

Kendre answered 29/8, 2017 at 19:15 Comment(0)
J
2

The reason you can't do this is that you cannot reassign the receiver in an extension function.

It's not possible to change the value of the Boolean because it is immutable.

Jess answered 29/8, 2017 at 19:14 Comment(0)
P
0

The reason you can’t do this comes to a lack of implementation of Kotlin extension probably due to the fact Extension in Kotlin are resolved Statically (even probably really static). So 'this' in a static context doesn't make sense.

Plater answered 20/7, 2019 at 16:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.