Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean extension function

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.

like image 909
Bhuvanesh BS Avatar asked Aug 29 '17 19:08

Bhuvanesh BS


People also ask

What are extension functions?

Extension functions are a cool Kotlin feature that help you develop Android apps. They provide the ability to add new functionality to classes without having to inherit from them or to use design patterns like Decorator.

How do you call a function with an extension?

The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call. The swap(0,2) function pass the index value of list inside MutableList<Int>.

What is Boolean in Kotlin?

Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false.

What is true about extension function in Kotlin?

The Kotlin extension allows to write new functions for a class from a third-party library without modifying the class. The beauty of the extension functions is that they can be called in the usual way, as if they were methods of the original class and these new functions are called Extension Functions.


1 Answers

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.

like image 105
jrtapsell Avatar answered Sep 23 '22 13:09

jrtapsell