In kotlin we don't have a switch, we have a when operator:
when
fun doSomething(x: Int){ when { x == 1 -> … x == 2 -> … else -> … } }
It can take a parameter to match:
fun doSomething(x: Int){ when(x) { 1 -> … 2 -> … else -> … } }
And also you can put different stuff there…
fun doSomethingWithAFoo(foo: Foo){ when(foo){ is SubFoo -> { //… } foo.someProperty == someValue -> … else -> … } }
in the case of is SubFoo you get auto-cast. So you can use foo as a SubFoo
is SubFoo
foo
SubFoo
For me more than 3 else-if will complicate the reading of the code and in some languages will get you a wrong scenario…
else-if
Like the kotlin syntax that actually doesn't have an else-if expression (yes, in kotlin is an expression) so you can end in weird places:
github.com/angryziber/kotlin-puzzl...
In kotlin else if(…) is actually: else { if() }
else if(…)
else { if() }
So that's one reason at least to prefer when over else-if in kotlin.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
In kotlin we don't have a switch, we have a
when
operator:It can take a parameter to match:
And also you can put different stuff there…
in the case of
is SubFoo
you get auto-cast. So you can usefoo
as aSubFoo
For me more than 3
else-if
will complicate the reading of the code and in some languages will get you a wrong scenario…Like the kotlin syntax that actually doesn't have an
else-if
expression (yes, in kotlin is an expression) so you can end in weird places:github.com/angryziber/kotlin-puzzl...
In kotlin
else if(…)
is actually:else { if() }
So that's one reason at least to prefer
when
overelse-if
in kotlin.