When property access


#1

I find myself wishing that when supported the following on a very regular basis:

when (myString){
    .isNotEmpty() -> {

    }

    .length > 30 -> {

    }
}

or

when (myDoor){
    .isOpen -> {

    }

    .isClosed -> {

    }

    .isWooden -> {
        
    }
}

Have there been any other requests for this kind of syntax? It doesn’t seem messy to me, and seems more concise than an empty when with the full logic in each “case” block.

Any chance it could be added to the future roadmap for Kotlin?

Keep up the good work!


#2

You could use

when {
  myDoor.isOpen -> ...
  myDoor.isClosed -> ...
  myDoor.isWooden -> ...
}

Also you might be interested in this discussion about adding it to when. When desperately needs `it`
But I think the closest solution to your problem would be

myDoor.apply {
  when{
    isOpen   -> ...
    isClosed -> ...
    isWooden -> ...
  }
}

#3

As discussed on that thread, .run is a better choice here so that it yields whatever you have in ...


#4

Woops, your right.


#5

You could set up sort of a matcher-like thing: https://programmingideaswithjake.wordpress.com/2016/08/27/improved-pattern-matching-in-kotlin/amp/


#6

how about using with?

with(myDoor){
    when {
        isOpen -> { ... }
        isClosed -> { ... }
        isWooden -> { ... }
    }
}

Edit: just keep in mind that in this exemple, if you have a wooden door which happens to be open, only the isOpen block will be executed