Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin shorthand version for if(true)

Tags:

kotlin

In Javascript you can write

if (condition){
  console.log("")
}

as

condition && console.log("")

is there a similar syntax in koltin?

like image 630
Yazan Jaber Avatar asked Oct 19 '25 07:10

Yazan Jaber


1 Answers

Unlike Javascript, kotlin is strictly typed. Both side of the && operator must be a Boolean. You can do some meaningless equality check to achieve this, but it just makes things less readable. For examples:

condition && (println("Hello, world!") == Unit)

or

condition && (println("Hello, world!") == null)

Even ternary operator (c?a:b) is removed in kotlin and they suggest using if(c) a else b. So just stick with the if.

like image 167
Ricky Mo Avatar answered Oct 21 '25 00:10

Ricky Mo