i want to use when expression in this kind of situ...
# getting-started
z
i want to use when expression in this kind of situation
Copy code
when(string){
   null -> ...
   this.length>1 -> ...
   else ->
}
i resorted to this:
Copy code
when{
   this==null -> ...
   this.length>1 -> ...
   else ->
}
is this idiomatic solution?
👌 1
m
btw, you can escape your code with 3 backticks (```) to make it look better
z
ok I will from now 🙂
a
Copy code
when{
   this is Nothing -> ...
   this.length>1 -> ...
   else ->
}
Is the action of an empty String the same as a null? If so you could rewrite it as
Copy code
when{
   this is Nothing || this.length == 0-> ...
   else ->
}
z
ah,, no this is not a probem I was more wondering if I may call attrbute on the argument when(arg) in what i symbolicaly wrote as 'this.length'
a
Think I misunderstood the question, unfortunately
this
will not correspond to the subject of the
when
condition. To need to evaluate the branches using the name of the object outside the
when
block. Hope that makes sense
z
Ah... really aha... think is ... I was using this construct in special context
Copy code
fun String?.shortened(maxLen:Int=60) = when{
    this == null -> ""
    this.length<maxLen -> this
    else -> "${this.substring(0,maxLen)}...(+${this.length-maxLen})"
}
so I thought this was in this context reference to when argument... but in fact it is this as extended target
a
That's right
z
So is the way I worte it, good way?
a
that should be fine, I'd just compare it to Nothing rather than null though
z
aha.. I will look in dept at Nothing... it is a bit new concept for me.. that Any vs Nothing and Nothing vs void 🙂
a
You might find this blog post from @natpryce helpful: http://natpryce.com/articles/000818.html
z
Thanks Andy
a
@andyb how do you compare it to Nothing?
a
this is Nothing
a
but Nothing can be
Nothing
? (pun not intended)
null is Nothing
results in
false
a
Copy code
val test : String? = null

    when (test) {
        is Nothing -> println("I am Nothing")
        else -> println("I am $test.")
    }
This code prints out ""I am Nothing"
Interestingly this code is different & prints out "I am null" which indicates that it has gone into the
else
condition: val test : String? = null when { test is Nothing -> println("I am Nothing") else -> println("I populated $test.") }
That has really caught me out & it looks like it might be a bug
z
PLS 🙂 when you find out... if you will put it here 😄
But one more difference this compiles
Copy code
val alfa:String?=null
when{
    alfa == null -> print("nothing")
    alfa.length>1 -> print("${alfa.length}")
    else -> print("else")
}
this does not
Copy code
when{
    alfa is Nothing -> print("nothing")
    alfa.length>1 -> print("${alfa.length}")
    else -> print("else")
}
a
@andyb
test is Nothing == false
is a bug?