Movatterモバイル変換


[0]ホーム

URL:


This page is no longer maintained — Please continue to the home page atwww.scala-lang.org

Home

Scala Main Menu

Home »A Tour of Scala » A Tour of Scala: Pattern Matching

A Tour of Scala: Pattern Matching

Created by admin on 2008-07-05. Updated: 2008-12-21, 01:11

Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. 

Here is a small example which shows how to match against an integer value:

object MatchTest1extends Application {def matchTest(x: Int): String = xmatch {case 1=>"one"case 2=>"two"case _=>"many"  }  println(matchTest(3))}

The block with the case statements defines a function which maps integers to strings. The match keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.

Here is a second example which matches a value against patterns of different types:

object MatchTest2extends Application {def matchTest(x: Any): Any = xmatch {case 1 =>"one"case"two" => 2case y: Int =>"scala.Int"  }  println(matchTest("two"))}

The first case matches if x refers to the integer value 1. The second case matches if x is equal to the string"two". The third case consists of a typed pattern; it matches against any integer and binds the selector value xto the variable y of type integer.

Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes.

Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.

Scala Quick Links

Featured News

User login


will be sent securely

Create new account

Retrieve lost password

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland


[8]ページ先頭

©2009-2026 Movatter.jp