Receiving parameters in when statement


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 { 
} ?: 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?


You should probably read this topic.

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

or simply

sample?.toUpperCase() ?: fetchAnotherString()


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

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


If you like using it –

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