val total_breaks = //a random number
total_breaks match {
case i if(i < 0) => chartTemplate.setAttribute("totalBreaks", 0)
case _ => chartTemplate.setAttribute("totalBreaks", total_breaks)
}
I was thinking there was a function in Scala that could shorten this. I thought min did this but I guess not. I can’t seem to find documentation on min, max, etc.
Something like total_breaks.min(0). Display 0 if under 0 if not display total_breaks.
Also is there a way do something like this
(4 + 5) match {
case 0 => println("test")
case _ => println(_) //i need to display the number passed into match? Is this not possible?
}
If I do case i => println(i) is that the same as case _ => ? Is that the fallback?
There are methods
minandmaxdefined inGenTraversableOnce, and thus available on sequences. You can use them as:There is also
minandmaxdefined inRichInt, that work like operators on anything that can be converted toRichInt, typically your vanilla integers:So if you want something that returns your number, say
xifxis greater than0and0otherwise, you can write:That means you can rewrite your pattern-matching as:
For your second question,
_andiare both valid patterns that will match anything. The difference is that in the first case you do not bind what you have matched to a variable. Usingprintln(_)is wrong, though; as such, it corresponds to an anonymous function that prints its first argument. So if you don’t want to repeat the expression(4 + 5), you should indeed write your pattern and code as: