Receiving parameters in when statement


#1

EDIT
This has already been discussed here and there is an open issue for it.


Consider the following code for handing a nullable variable:

var sample: String? = ...;
sample?.let { 
  it.toUpperCase() 
} ?: run { fetchAnotherString() }

As far as I know, this is the best way to have two branches with a nullable variable, but I think this would be much better:

when (sample) {
  !null -> it.toUpperCase()
  else -> fetchAnotherString()
}

Are there limitations preventing this from being possible?


#2

You should probably read this topic.


#3
when {
  sample != null -> sample.toUpperCase()
  else -> fetchAnotherString()
}

or simply

sample?.toUpperCase() ?: fetchAnotherString()

#4

Thank you @darksnake, I believe that makes this topic redundant.

@fvasco that doesn’t work for mutable properties like let does.


#5

If you like using it –

sample.let { when (it) {
    it != null -> it.toUpperCase()
    else -> fetchAnotherString()
}}