How to use ternary operator(?:) or Null Coalescing operator(??) to write if-else condition?

僤鯓⒐⒋嵵緔 提交于 2020-11-29 09:58:19

问题


if(country1!=null)

  { 

country1="Turkey"; 

  }
  else
  {

country1= "ABD";

  } 

回答1:


Ternary operators use three operands:

A condition followed by a ?, followed by an expression to evaluate if the condition is 'truthy', followed by a :, followed by an expression to evaluate if the condition is falsey.

So in your case, what you'd want to do is this:

country1 = country1 != null ? 'Turkey' : 'ABD';

EDIT:

You seem a little confused about ?? operator. ?? is called Null Coalescing operator

x = x ?? 'foo';

is equivalent to

if( x == null )
    x = 'foo';
else
    x = *whatever the value previously was*;

so if we have x set to bar before the check, it won't change to foo because bar is not equal to null. Also, note that the else statement here is redundant.

so ?? will set the variable to some value only if it was previously null.

In your code, you are trying to assign one of the two values Turkey or ABD, and not a single value if the previous value was null. So you get a syntax error.

So, to summarize.

if() {}
else {}

can be shortened using the ternary operator ? :.

and

if(){}

can be shortened using the ?? operator, because the else statement here will simply be redundant.

Thus, the equivalent of your code won't use ?? operator.




回答2:


var s = country1 != null ? "Turkey" : "ABD";



回答3:


final result = country1 != null ? 'Turkey' : 'ABD';



回答4:


Syntax: var result = a != null ? condition is true then further code : condition is false then further code;

in your case : var result = country1 != null ? "Turkey" : "ABD";




回答5:


you can do it this way too:

final result = "${country1 != null ? 'Turkey' : 'ABD'}";


来源:https://stackoverflow.com/questions/58910273/how-to-use-ternary-operator-or-null-coalescing-operator-to-write-if-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!