3
gitpush
5y

Can someone please explain the benefits of this in Kotlin:

var x = if(a !=b) {
z
}else{
y
}

Even for a conditions with one line body it looks bad in reading and getting a clue of what does this do.

I mean whats wrong with:
var x: MyObject

if(a!=b){
x = y
}else{
x = z
}

Even in switch cases (or as kotlin calls: when) True one return source, but now good luck finding the last line that is the actual returned value ...

Comments
  • 2
    Isn't it kinda like python? Their version of ternarys? Nah idk... I've wondered as well
  • 1
    @ScriptCoded How is it like in Python?
  • 2
    @gitpush more readable
    x = z if a != b else y
  • 2
    @vane well this assuming all vars are called a b c d e ...etc.

    Imagine a veryLongVarNameForNoDamnReasonWeAllSawSuchNamesAndDroveUsCrazy

    Personally, I wouldn't want to imagine a long var name lol
  • 3
    @gitpush we don’t do java naming here, variables are named very_long_variable_name and there is line length limit in pep8 so we can focus on solving problems not creating new ones except python 2 to 3 of course :)
  • 2
    @vane good point. Let's hope I get to know why Kotlin has this lol
  • 5
    @gitpush I think you can skip braces like in javascript so it can be more nice
    var x = if (a != b) y else z
  • 2
    @vane Yes we can, and it looks better like that tbh
  • 2
    @gitpush yeah those new languages look all the same right now:
    kotlin, swift, go, scala, es6 js

    differences are cosmetic
  • 1
    @gitpush Your example only works with var, but one may want to use val to ensure it can't be reassigned.
  • 2
    @vane lool trying to keep up with JS frameworks I see
  • 0
    In Kotlin, "if" (just like "when") has a classic statement-version and an expression-version.
    I think it is for consistency reasons.
    But I also do miss the classic ?: syntax from most c like languages :(
  • 1
    Don't use {} in what should be a one liner.
  • 0
    Echoing what everyone else has said, but it's designed to be a more readable ternary replacement. If you start needlessly formatting ternaries over multiple lines with braces, then yeah - it looks odd.
  • 1
    If you find an if expression less readable than an if statement, your brain is too ingrained in procedural programming. Work with any (even halfway) functional programming language for a while, and you will not want to miss the if expression anymore.

    And yes, the if expression is equivalent to the ternary operator expression in C/C++/C#/Java.
Add Comment