In 'Programming in Scala, Second Edition' at page 410 you can find class Simulation which have the following method:
private def next() {
(agenda: @unchecked) match {
case item :: rest =>
agenda = rest
curtime = item.time
item.action()
}
}
I'm curious why Odersky implemented this with pattern matching rather than just like that:
private def next() {
val item = agenda.head
agenda = agenda.tail
curtime = item.time
item.action()
}
Is pattern matching so efficient that it doesn't matter at all? Or it was just not so perfect example?
Normally I'd write it the way you did. (Even though pattern matching is quite efficient, it is not as efficient as head/tail.) You'd use pattern matching if
MatchException
instead of a NoSuchElementException
There are a couple reasons:
Part of the point of the book is to get you thinking in Scala (functional) terms; pattern matching is the functional-programming equivalent.
Pattern matching and the functional approach are the natural pattern in Scala, and allow things like concurrency in a natural way; learn that pattern and your Scala programs will be ready for more advanced uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With