Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

14.2. Guards

Suppose we want to extend our example to match all digits. In a C-style switch statement, you would simply add multiple case labels, for example case '0': case '1': ... case '9':. (Except that, of course, you can’t use ... but must write out all ten cases explicitly.) In Scala, you add a guard clause to a pattern, like this:

ch match {
  case '+' => sign = 1
  case '-' => sign = -1
  case _ if Character.isDigit(ch) => digit = Character.digit(ch, 10)
  case _ => sign = 0
}


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial