为什么这种模式匹配不起作用?

时间:2013-03-30 17:16:10

标签: scala pattern-matching

我有一个通用类Book[T](index: Int, type: T)和一个foo类型的对象Book。我不知道如何访问索引和类型。我试过了:

1. foo match { case Book[T](index: Int, type:T) => {} }
2. foo match { case Book(index: Int, type:T) => {} }
3. foo match { case foo: Book[T] => { foo.index } }

所有邮件都失败了:

1. class Book does not take type parameters
2. class Book not found
3. index is not a member of Book

谢谢。

1 个答案:

答案 0 :(得分:1)

type是scala已经使用过的关键字。 您可以尝试使用其他关键字代替type并使用case class进行模式匹配来实现相同目标。

 case class Book[T](index: Int, bookType : T)

  val foo =  Book(1,Book)                         

  // foo  : stack.Book[stack.Book.type] = Book(1,Book)

  foo match {
    case Book(i,t) => "index : " + i + ", type : " + t // play around with i & t
  }                                     

 //> res0: String = index : 1, type : Book