Reputation: 41
I have code like this:
val s = someOtherObject.subObjects().size match {
case size > 0 => "Size is greater than 0"
case _ => "Size is less than 0"
}
How do I assign the value of someOtherObject.subObjects().size in the match clause to the size variable in the case statement
Do I have to do :
val size = someOtherObject.subObjects().size
val s = size match {
case size > 0 => "Size is greater than 0"
case _ => "Size is less than 0"
}
Upvotes: 1
Views: 99
Reputation: 480
You can give that variable a name and return it back like this:
val s = someOtherObject.subObjects().size match {
case size if size > 0 => size
case size @ _ => size
}
Or you can simply use if
expressions:
val size = someOtherObject.subObjects().size
val result = if(size > 0) {
// Size is greater than zero
size
} else {
// Size is less than or equal to zero
size
}
Upvotes: 0
Reputation: 366
val s = size match {
case x if x > 0 => ("Size is greater than 0", x)
case x @ _ => ("Size is less than 0", x)
}
s will be tuple (String, Int)
s._1 will be string message
s._2 will be value of size.
Upvotes: 2