9

So in java we have the ternary operator (?), which sometimes is useful to easy some value computed by a if-else inlines. For example:

myAdapter.setAdapterItems(
            textToSearch.length == 0
            ? noteList
            : noteList.sublist(0, length-5)
)

I know the equivalent in kotlin would be:

myAdapter.setAdapterItems(
                if(textToSearch.length == 0)
                    noteList
                else
                    noteList.sublist(0, length-5) 
)

But i just used to love the ternary operator in Java, for short expression conditions, and when passing values to a method. Is there any Kotlin equivalent?

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
johnny_crq
  • 4,291
  • 5
  • 39
  • 64

1 Answers1

18

There is no ternary operator in Kotlin.

https://kotlinlang.org/docs/reference/control-flow.html

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

You can find a more detailed explanation here.

Eric Cochran
  • 8,414
  • 5
  • 50
  • 91
  • 18
    Not a big fan of this, tbh – Kirill Rakhman Jan 22 '16 at 08:21
  • 3
    Maybe it is to avoid confusion with `?:` and `?` followed by `:` ... but I miss having it. – Jayson Minard Jan 22 '16 at 12:17
  • @JaysonMinard I feel like being able to use `if` in an infix form would take away much of the boilerplate. – Jire Jan 24 '16 at 10:19
  • @KirillRakhman @JaysonMinard Something like this isn't _too_ unclear to me: `(textToSearch.length == 0) +noteList -noteList.sublist(0, length-5)` I implemented it like this: https://gist.github.com/Jire/46b1ee35855a5e97bfd5 – Jire Jan 24 '16 at 11:07
  • 7
    The decision to use `if...else` as an expression probably goes along with the decision to use `when` (similar to switch) as an expression. But I think that replacing `a ? b : c` with `if(a) b else c` goes against the goal to make Kotlin more concise and readable then Java. – Love Mar 11 '16 at 15:02
  • I think `Array>` also goes against that goal - luckily for some reason I don't use arrays nearly as much as I used to. but every time I have to type `if() else` I get annoyed.. usually because I want to insert it into areas that verbosity is very undesirable – ycomp Aug 28 '17 at 04:38