Kotlin equivalent of ternary operator [duplicate] - ternary-operator

This question already has an answer here:
Kotlin Ternary Conditional Operator
21 answers
So in java we have the ternary operator (?), which sometimes is useful to easy some value computed by a if-else inlines. For example:
textToSearch.length == 0
? noteList
: noteList.sublist(0, length-5)
I know the equivalent in kotlin would be:
if(textToSearch.length == 0)
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?

There is no ternary operator in Kotlin.
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.


Comparison of Ternary operator, Elvis operator, safe Navigation Operator and logical OR operators

Comparison with Ternary operator vs Elvis operator vs safe Navigation Operator vs logical or operators in angular
Ternary Operator(statement ? obj : obj)
let gender = user.male ? "male" : "female";
Elvis Operator (?: )
let displayName = user.name ?: "";
Safe Navigation Operator (?.)
let displayName = user.name ?. "";
Logical or operators
let displayName = user.name || "";
The above all operators are similarly doing the same process. What are the difference benefits and which one is best & worst?
Maybe I've missed a couple versions, but to my knowledge, TypeScript does not have an elvis operator or a safe navigation operator. The only extra thing they have is a non-null assertion operator !., but this is only for the compiler, and in the compiled js the ! will be removed. Angular however, does have the safe navigation operator inside their templates, but under the hood this will resolve into a logical or ||. The benefit here is increased readability and smaller templates.
Besides that, TypeScript does have the ?: notation, but this is used in interfaces or method parameters to indicate that the value is optional
Which leaves us with the ternary operator vs logical or. You would use the first one if there are 3 values. The question, the answer yes result, and the answer no result to said question.
And the latter when there are 2 values. Where the first one, if resolved to truthy will be the answer, and otherwise the second one, regardless of its value.
Benefit wise, I can't really say much. I would expect them to be equally fast, with a marginal difference. Perhaps readability is increased with the ternary option, which you obviously can always use instead of the logical or ||, but personally I like to use the ||, because it keeps the code compact.
Ternary Operator
Simplified if else, available everywhere
Elvis operator ?:
Not available in typescript/javascript/angular and essentially the same as ||
Safe navigation operator ?.
Only available in angular templating, used to prevent null pointers in object parameter navigation
Logical or ||
If not left hand, then right hand. Even more simplified if else. Available in typescript/javascript/angular
let gender = user.male ? "male" : "female";
can Used in javascript(Typescript) as well as in HTML tag binding ,
Basically when you use this operator in javascript code it means if first statment is true than execute first otherwise execute second option
In angular2 Terms Ternary Operatoris known as Safe Navigation Operator (?.) or you can use the term Elvis Operator (?: ) which is used at the time of fetching asynchronous data from the backend or some kind of databse.
alternate :- you can also use Elvis Operator (?: ) in angular2 template like this (we can say this is shorthand property)
let gender = user.gender || "";
Have a look here too
Replacement of Elvis Operator of Angular2 in Typescript
Safe Navigation Operator (?.) which is also wrongly called Elvis operator in Angular2 only
this is an Angular2 template binding thing, it's not available in javascript.
Ternary Operator(statement ? obj : obj)
This when you want to check for a condition and if that condition is truthy, return a value or if it's falsy return another value.
Logical or operators
This when you want to return a value based on it's own existence or truthiness (so there is no other rule involved), it's very different from Ternery.
let displayName = user.name || "";
In above example, you're saying if either of those expression are truthy, return it, where is in bellow :
let gender = user.male ? "male" : "female";
What you're saying is : if my condition is truthy , return "male" otherwise return "female"
Elvis Operator (?: )
This is NOT available in javascript and you could find it in other languages like PHP and it's basiacly the same as Ternery operator, but simplified , in a case where the left side of the comparison ( the truth side ) can be used as the returned value :
so :
let m = something ?: somethingElse // if in case of truthiness of `something` you want to return `something` , you can do this
is equal to :
let m = something ? something : somethingElse
EDIt :
It doesn't make sense to compare them, they're not doing the same thing at all.
#Milad RameshRajendran you can use the term elvis instead of Safe Navigation Operator (?.) in angular2, according to me both are same don't confuse with name
I got something from this source:
Elvis Operator (?: )
The "Elvis operator" is a shortening
of Java's ternary operator. One
instance of where this is handy is for
returning a 'sensible default' value
if an expression resolves to false or
null. A simple example might look like
def gender = user.male ? "male" : "female" //traditional ternary operator usage
def displayName = user.name ?: "Anonymous" //more compact Elvis operator
Safe Navigation Operator (?.)
The Safe Navigation operator is used
to avoid a NullPointerException.
Typically when you have a reference to
an object you might need to verify
that it is not null before accessing
methods or properties of the object.
To avoid this, the safe navigation
operator will simply return null
instead of throwing an exception, like
def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown
But I want to know the above all operators are similarly doing the same process. What are the difference benefits and which one is best & worst?

Simulate ternary operator in Elixir

How to do the similar conditional one-line check in Elixir?
if (x > 0) ? x : nil
Is this the only equivalent in elixir world?
if true, do: 1, else: 2
To me, the if IS the equivalent of a ternary operator as it evaluates to a value which for various other languages it doesn't.
so x = if false, do: 1, else: 2
is basically x = false? 1 : 2
Not sure why Ruby adopted it ( if you are coming from Ruby ) as it has assignable if statements. in C the ternary is useful as the code bloats with the equivalent if statements. Of course C programmers desperate for terseness went nuts and did many nested upon nested ternaries :)
Yes, there's nothing like a ternary operator in Elixir. The keyword version of if is probably the closest thing.
if condition, do: true_expr, else: flase_expr
I saw this alternative in an tweet,
is_it_true && "TRUE" || "FALSE"

Why doesn't Kotlin support “ternary operator”

Explain: This question is more about the design intentions of Kotlin. Many expression languages support both Ternary operator and if expression [e.g., Ruby, Groovy.]
First of all, I know Groovy supports both Ternary operator and Elvis operator: Ternary operator in Groovy. So I don't think it's a syntax problem.
Then the official documents said:
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.
And this doesn't convince me. Because Kotlin support Elvis operator which ordinary if works just fine in that role either.
I think ternary operator is sometimes better than ordinary if, though I wonder why doesn't Kotlin just support ternary operator?
Because if .. else .. works fine. Take a look:
fun main(args: Array<String>) {
var i = 2
println("i ${ if(i == 1) "equals 1" else "not equals 1" }")
In languages which have ternary operator you use it like this
String value = condition ? foo : bar;
In Kotlin you can do the same thing using if and else
var value = if(condition) foo else bar;
Its bit verbose than the ternary operator. But designers of Kotlin have thought it is ok. You can use if-else like this because in Kotlin if is an expression and returns a value
Elvis operator is essentially a compressed version of ternary conditional statement and equivalent to following in Kotlin.
var value = if(foo != null) foo else bar;
But if Elvis operator is used it simplify as follows
var value = foo ?: bar;
This is considerable simplification and Kotlin decided to keep it.
Ternary operator has its problems, for example it is hard to read with big expressions. Here is a line from my C++ project where I used ternary operator:
const long offset = (comm_rank > 0) ? task_size_mod + (comm_rank - 1) * task_size : 0;
I would rather use an if else expression here since it is so much more visible.
Answering you question, I am aware of two reasons why ternary operator was not implemented in Kotlin:
1) Since if else is an expression anyway, it can replace ? :
2) Experience from other languages (C++) shows that ? : provokes hard-to-read code, so it is better to be left out

Limit operator (if variable>value then variable=value)

Is there such a thing as a Limit operator that lets you control the maximum or minium value of a variable.
if variable > value then variable = value
My question is not language specific, but answers in different languages are appreciated (esp. Delhpi).
I know operators differ from language to language, but mostly in syntax.
Would an operator like this be usefull enough?
Some languages have "min" operator that can be used for this: variable = min(variable, limit)
Basically, an operator is nothing else than a function.
Unary operators like ! (not) can be mapped with the function
Boolean not(Boolean)
Binary operators like + (plus) can be mapped with the function
Integer plus(Integer, Integer)
So, you can define any missing "operator" on your own as a function. Many languages don't allow to define operators on your own. In Groovy you can overload existing operators:

Does the shorthand ternary operator make multiple calculations?

The ternary operator has a shorthand version, i.e.
var = exp ?: exp2
I know it works in PHP. Other languages may have also picked it up. C# has similar functionality (for the context of this question) - ??.
When the condition passes, is the expression evaluated again, or is the result stored somewhere?
The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
It is stored, not computed twice.