# Add "if" method to boolean type (Early return alternative)

**URL:** <https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032>\
**Category:** Libraries\
**Created:** [October 11, 2016, 3:47pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032 "2016-10-11T15:47:56Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![milosz.moczkowski](https://avatars.discourse-cdn.com/v4/letter/m/f4b2a3/32.png) [@milosz.moczkowski](https://discuss.kotlinlang.org/u/milosz.moczkowski)\
**Post date:** [October 11, 2016, 3:47pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/1 "2016-10-11T15:47:56Z")

</div>

Instead of writting:

```
fun foo() {
    if(!bar) return // early return

    // perform operations
}

```

It would be nice to have a convenient method like:

```
fun foo() = bar.if { /* executed only if bar is true */ }

```

We can already do that for nulls:

```
fun foo() = bar?.let { /* executed only if bar is non-null */ }

```

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [October 11, 2016, 3:53pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/2 "2016-10-11T15:53:50Z")

</div>

How is `bar.if { ... }` better than `if (bar) { ... }`, other than that it saves a single character?

---

<div class="post-metadata">

**Author:** ![AndroidGuyDD](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/androidguydd/32/2166_2.png) [@AndroidGuyDD](https://discuss.kotlinlang.org/u/AndroidGuyDD)\
**Post date:** [October 11, 2016, 4:00pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/3 "2016-10-11T16:00:02Z")

</div>

It enforces the quick return mantra when your method code should only run after one guard clause.  
if (bar) { … }  
creates a unnecessary indentation.

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [October 11, 2016, 4:01pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/4 "2016-10-11T16:01:02Z")

</div>

I don’t think I follow. `bar.if { ... }` creates exactly as much indentation as `if (bar) { ... }`. Both can be used as an expression body of a method.

---

<div class="post-metadata">

**Author:** ![milosz.moczkowski](https://avatars.discourse-cdn.com/v4/letter/m/f4b2a3/32.png) [@milosz.moczkowski](https://discuss.kotlinlang.org/u/milosz.moczkowski)\
**Post date:** [October 11, 2016, 4:02pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/5 "2016-10-11T16:02:01Z")

</div>

1. You can say exactly the same about `?.let`. You could just write `if(bar != null) {...}`

2. You seldom write:

Instead, you write an early return statement:

```
fun foo() {
    if(!bar) return

   // stuff
}

```

This proposal would simplify it even further. It improves readability, maintenance and keeps syntax neat.

---

<div class="post-metadata">

**Author:** ![yole](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/yole/32/1425_2.png) [@yole](https://discuss.kotlinlang.org/u/yole)\
**Post date:** [October 11, 2016, 4:17pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/6 "2016-10-11T16:17:54Z")

</div>

The main advantage of `let` is that it allows you to avoid repeating a longer expression. `if (x.foo.bar.baz != null) { x.foo.bar.baz.doSomething()` becomes `x.foo.bar.baz?.let { it.doSomething() }`. Your proposed function has no such benefit.

I don’t see at all why, if you prefer to use early return statements to `if` blocks surrounding the entire function, you’d suddenly stop using early return statements if `if` becomes a method instead. The advantages and disadvantages of early returns are not affected in any way by the shape of the `if` condition.

And finally, if you like this style and want to use it in your project, you’re welcome to do so: it takes exactly one line of code to define an extension function `Boolean.ifTrue`.

---

<div class="post-metadata">

**Author:** ![ilya.gorbunov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ilya.gorbunov/32/1645_2.png) [@ilya.gorbunov](https://discuss.kotlinlang.org/u/ilya.gorbunov)\
**Post date:** [October 11, 2016, 5:15pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/8 "2016-10-11T17:15:50Z")

</div>

Could you elaborate what is the signature of the proposed function?

---

<div class="post-metadata">

**Author:** ![Oliver\_Plohmann](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/oliver_plohmann/32/2398_2.png) [@Oliver\_Plohmann](https://discuss.kotlinlang.org/u/Oliver_Plohmann)\
**Post date:** [October 11, 2016, 7:38pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/9 "2016-10-11T19:38:09Z")

</div>

Hi Milosz,

what you are suggesting is the way things are done in Smalltalk. There are methods named ifTrue: / ifFalse: in class True and False, which are subclasses of Boolean. They have a single instance true and false. Let’s hava a look at some Java-ish Smalltalk expression that evaluates to a boolean:

[System.currentTimeInMillis % 2 == 0]  
ifTrue: [println(“even”)]  
ifFalse: [println(“uneven”)]

Closures in Smalltalk are surrounded by square brackets. So for the example above code not to fail at runtime there needs to be a method in class Closure named ifTrue:ifFalse:

In Smalltalk there is no for loop. Looping is done through collection iterators. 36 years after Smalltalk-80 Java also has them and they are called streams and they are really ugly. Better stick to Groovy/Kotlin/Scala/Javaslang. Really ;-). Other than that for looping over an integer range there is a method to:do:, for example:

1 to: 12 do: [:index | Transcript cr; show: i printString]

This time no Java-ish Smalltalk code but some real one. So the message to:do: is sent to the object 1 with the first parameter 12 and the second parameter being a unary closure (closure with one parameter). For this to work the method to:do: needs to be put into class Integer.

This way, in Smalltalk, neither conditional expressions nor loops are part of the language. They are implemented as methods in the applicable classes where the receiver object is instantiated from.

When Java came along it basically killed Smalltalk, which had a period of success inside banks and insurance companies (because IBM back then promoted Smalltalk). In Java loops and conditional expressions where keywords of the language and built into the compiler. Advantage being efficiency and better performance compared to dynamic method dispatch as in Smalltalk.

Since Kotlin already has conditionals and loops as part of the language there is little point in providing them again some other way. People are not used to the way things are done in Smalltalk. It confuses them a lot when they see things being done that way. They want things to be done as in the “traditional” way. Another question is whether there is a closure class in Kotlin you can add methods to through extension methods. I guess there is. But the whole thing would appear awkward to most people and especially the developers reading your code.

---

<div class="post-metadata">

**Author:** ![hsk3mis](https://avatars.discourse-cdn.com/v4/letter/h/a3d4f5/32.png) [@hsk3mis](https://discuss.kotlinlang.org/u/hsk3mis)\
**Post date:** [February 20, 2018, 9:56am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/10 "2018-02-20T09:56:22Z")

</div>

For sure having `bar.if { ... }` is redundant, but it gives a lot to readability in case of longer stream-like function chains that terminates with a Boolean result (eg. any(), all())  
`someStream.map().filter().any().if {...}` is much more readable than if you have to wrap whole expression into `if`.

Of course there have to be limits to the wish-list, but the proposal is ok in itself 😉

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [February 20, 2018, 10:05am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/11 "2018-02-20T10:05:22Z")

</div>

I would disagree. I think most people are used to look for the condition after the `if`, making your example less readable. Also there is a problem with the name. `if` is a keyword and can therefor not be used as a function name. Normally you could just add a function like this to the std lib but in this case you would need to create a new language construct allowing the name `if` to be used.

---

<div class="post-metadata">

**Author:** ![hsk3mis](https://avatars.discourse-cdn.com/v4/letter/h/a3d4f5/32.png) [@hsk3mis](https://discuss.kotlinlang.org/u/hsk3mis)\
**Post date:** [February 20, 2018, 11:08am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/12 "2018-02-20T11:08:29Z")

</div>

Of course name `if` would be confusing. Smalltalk like `ifTrue` would be much better.  
I believe that more and more people are getting used to functional style of programming and this kind of constructs (eg. Java Optional) are getting in popularity.

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [February 20, 2018, 11:11am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/13 "2018-02-20T11:11:35Z")

</div>

I would not mind adding `ifTrue` and `ifFalse` to the std lib.

---

<div class="post-metadata">

**Author:** ![brymher](https://avatars.discourse-cdn.com/v4/letter/b/f17d59/32.png) [@brymher](https://discuss.kotlinlang.org/u/brymher)\
**Post date:** [September 11, 2019, 2:25pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/14 "2019-09-11T14:25:40Z")

</div>

you can create an extension

fun Boolean.If(action: () → Unit): Boolean {  
if (this) action()  
return this  
}

fun Boolean.Else(action: () → Unit): Boolean {  
if (!this) else action()  
return this  
}

but there is still no much saved really

---

<div class="post-metadata">

**Author:** ![vtb](https://avatars.discourse-cdn.com/v4/letter/v/0ea827/32.png) [@vtb](https://discuss.kotlinlang.org/u/vtb)\
**Post date:** [September 18, 2019, 10:36am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/15 "2019-09-18T10:36:14Z")

</div>

> [@brymher](#):
>
> fun Boolean.Else(action: () → Unit): Boolean {  
> if (!this) else action()  
> return this  
> }

“If” and “Else” are ambiguous function names.

```
inline fun Boolean.yes(block: () -> Unit) = also { if (it) block() }

inline fun Boolean.no(block: () -> Unit) = also { if (! it) block() }

```

---

<div class="post-metadata">

**Author:** ![benchuknii](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/benchuknii/32/7551_2.png) [@benchuknii](https://discuss.kotlinlang.org/u/benchuknii)\
**Post date:** [May 19, 2020, 6:08am UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/16 "2020-05-19T06:08:26Z")

</div>

also this syntax is useful for null checks  
bar?.ifTrue { … }

---

<div class="post-metadata">

**Author:** ![sollecitom](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/sollecitom/32/3552_2.png) [@sollecitom](https://discuss.kotlinlang.org/u/sollecitom)\
**Post date:** [June 2, 2020, 9:17pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/17 "2020-06-02T21:17:59Z")

</div>

With the standard library:

```auto
val condition = true
condition.takeUnless { false }?.let { println(it) }
condition.takeIf { true }?.let { println(it) }

```

---

<div class="post-metadata">

**Author:** ![spyro](https://avatars.discourse-cdn.com/v4/letter/s/54ee81/32.png) [@spyro](https://discuss.kotlinlang.org/u/spyro)\
**Post date:** [September 3, 2020, 4:53pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/19 "2020-09-03T16:53:32Z")

</div>

```
fun <T>Boolean.ifTrue(supplier: () -> T) = if (this) supplier() else null

```

(And yes, this should be included)

---

<div class="post-metadata">

**Author:** ![fatjoe79](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fatjoe79/32/4221_2.png) [@fatjoe79](https://discuss.kotlinlang.org/u/fatjoe79)\
**Post date:** [September 3, 2020, 9:46pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/20 "2020-09-03T21:46:12Z")

</div>

If you declare that function as inline, then it can be used for non-local returns also.

---

<div class="post-metadata">

**Author:** ![dalewking](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/dalewking/32/1496_2.png) [@dalewking](https://discuss.kotlinlang.org/u/dalewking)\
**Post date:** [September 8, 2020, 3:20pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/21 "2020-09-08T15:20:21Z")

</div>

I would also allow nullable boolean as in:

```
inline fun <T>Boolean?.ifTrue(supplier: () -> T) = if (this == true) supplier() else null

```

So you can do:

```
return functionReturningNullableBoolean().ifTrue { "yes" } ?: "no"

```

---

<div class="post-metadata">

**Author:** ![fatjoe79](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/fatjoe79/32/4221_2.png) [@fatjoe79](https://discuss.kotlinlang.org/u/fatjoe79)\
**Post date:** [September 8, 2020, 4:35pm UTC](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032/22 "2020-09-08T16:35:59Z")

</div>

You don’t need to declare the boolean as nullable to achieve that feature:

```
inline fun <T>Boolean.ifTrue(supplier: () -> T) = if (this == true) supplier() else null

val bool1: Boolean = Todo()
val s1 = bool1.ifTrue { "yes" } ?: "no"

val bool2: Boolean? = Todo()
val s2 = bool2?.ifTrue { "yes" } ?: "no"

```

This gives you a bit more control over how nullable argument should be handled.

[Next page](https://discuss.kotlinlang.org/t/add-if-method-to-boolean-type-early-return-alternative/2032.md?page=2)
