LoginSignup
0
0

More than 5 years have passed since last update.

普通のクラスとケースクラスのパターンマッチ

Last updated at Posted at 2015-06-25

Scalaの便利な機能パターンマッチ、いろいろな場面で使えるけど、普通のクラスとケースクラスで微妙な差異が・・・・

PatternMatch
object PatternMatch {

  class A

  class B extends A
  class C extends A

  case class X(name: String) extends A
  case class Y(name: String) extends A

  def matchNoCaseClass(obj: A): Unit = obj match {
    case a: B => println("class B")
    case _ => println("other")
  }

  def matchCaseClass(obj: A): Unit = obj match {
    case X(_) => println("class X")
    case _ => println("other")
  }

  def main(args: Array[String]) = {
    matchNoCaseClass(new B)
    matchNoCaseClass(new C)

    matchCaseClass(new X(""))
    matchCaseClass(new Y(""))
  }

}

実行結果は以下のような感じ。

class B
other 
class X
other

普通のクラスだとパターンマッチのcase節にコンストラクタ縛りとかが使えない。そもそも以下の型縛りの書き方もできない。

case B => println("class B")     // 文法エラー
case b: B => println("class B")  // OK
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0