Someone has probably already proposed this, (if so...
# language-proposals
s
Someone has probably already proposed this, (if so please post the link) but I would find this syntax handy for when subjects
Copy code
when(someObject){
  .hasSomeProperty() -> doSomething
  .isBetterThan(someValue) -> doSomethingElse()
  else -> doAThirdThing()
}
Where
hasSomeProperty()
and
.isBetterThan
are either member or extensions functions on
someObject
1
k
Copy code
fun someObject.myEffect() {
  when{
    hasSomeProperty() -> doSomething
    isBetterThan(someValue) -> doSomethingElse()
    else -> doAThirdThing()
  }
}
or you can just use the someObject inside the
when
Copy code
when{
    someObject.hasSomeProperty() -> doSomething
    someObject.isBetterThan(someValue) -> doSomethingElse()
    else -> doAThirdThing()
  }
why do you think when() with a scope would be a good pick?
s
Putting the someObject inside the when block requires a bit more cognitive load to process, particularly if you have similarly names variables in scope. The first option you suggested is nicer, but sometimes its more readable and easier to comprehend to have these when statements inline, rather than breaking into a separate function.
c
Copy code
with(someObject) {
    when {
        hasSomeProperty() ->
        isBetterThan(someValue) ->
        else ->
    }
}
Not as concise but might be a nice hack for the short-term?
s
yes, I like that, thanks 🙂
👍🏻 1
l
its a nice hack, but i actually really like the proposed syntax. I think most of the issues with having
when
introduce a receiver scope by itself (which has been proposed many times) are about backwards-compatibility and ambiguity. making this a special syntax, where you can use
.method()
would solve the compabibility problems and would be a great improvement to readability in many cases. it's also not that far of the currently existing syntax for
is
, where normally you do
if(foo is Bar)
but in when you just do
when(foo) { is Bar -> {} }
which in essence is the exact same idea of just leaving out the variable name within the when clause whilst typing everything else like you'd need to in an if-statement I'd love and support an actual language proposal for this! go for it, man
👍 2
k
Implicit Member Expressions! I love these so much in Swift. I think there’s a youtrack out for them