Add ternery operator

I love Kotlin, it’s so neat and elegant. :+1: :+1: :+1:

When I learned about Kotlin a few years ago, I was surprised to find that I couldn’t write a ? b : c, which is common in many other languages. Of course, I can use if (a) b else c instead, but it’s not neat.

After using Kotlin for a few years, I still think that the ternary operator should be supported. It’s the only obvious disadvantage I can think of (compared to Java).

I noticed this post, but it’s closed. Hope the ternery operator can be reconsidered.

1 Like

Been, discussed to death in many other threads. It ain’t gonna happen, thank goodness.

3 Likes

I will say however here is a utility method I created for our code base that comes in handy sometimes:

inline fun <T> Boolean.map(ifTrue: T, ifFalse: T) =
    if (this) ifTrue else ifFalse

which allows you to say

    a.map(b, c)

though it may not cover all cases

Yes, it’s not ideal because b and c will always be evaluated.

I do like the C-based conditional ternary operator. But, there are actually more languages that do not support it - such as some recent ones (eg. Rust, Julia, Nim and Crystal) and older popular ones like Python and Lua. Scala which inspired some aspects of Kotlin also chose not to implement it either.

  1. Python
  2. Rust
  3. Crystal
  4. Nim (though it has a similar construct)
  5. MATLAB
  6. Pascal
  7. COBOL
  8. Fortran
  9. Lua
  10. Julia
  11. Erlang
  12. Elixir
  13. Ada
  14. Modula-2
  15. R
  16. TCL
  17. Smalltalk
  18. Prolog
  19. Bash and most shell scripting languages
  20. Scratch
  21. Scala
  22. Kotlin

Lisp family:
23. Common Lisp
24. Emacs Lisp
25. AutoLisp
26. Clojure
27. ISLISP
28. PicoLisp
29. newLisp

Scheme family:
30. Racket
31. Chez Scheme
32. Chicken Scheme
33. Gambit
34. Guile
35. MIT Scheme
36. Bigloo
37. Kawa

Forth family:
38. ANS Forth
39. fig-Forth
40. iForth
41. SwiftForth
42. gForth
43. pForth
44. ColorForth
45. 8th

BASIC family:
46. Visual Basic
47. VBScript
48. B4X (B4A, B4i, B4J, B4R)
49. QBasic
50. FreeBASIC
51. PureBasic
52. Liberty BASIC
53. SmallBASIC
54. BBC BASIC
55. Gambas

ML family:
56. Standard ML
57. OCaml
58. F#

Hardware Description Languages:
59. VHDL
60. Verilog

  1. ABAP
  2. Logo
  3. Alice
  4. Inform 7
  5. APL
  6. J
  7. Occam
  8. Oberon
  9. Io
  10. Eiffel
  11. Mathematica/Wolfram Language
  12. LabVIEW
  13. REXX
  14. PL/I
  15. Algol
  16. Simula
  17. Maple
  18. Ladder Logic (used in PLCs)
1 Like

Yeah, I generally only use it for things that are not computed. Most often for choosing between 2 string resources for the UI based on a boolean such as this other function I have:

val Boolean.toYesNo: StringDesc get() = map(yes_label, no_label)