构造函数无法实例化为预期类型; p @ Person

时间:2013-02-21 06:51:15

标签: scala scala-2.9

我使用的是scala版本:Scala code runner version 2.9.2-unknown-unknown -- Copyright 2002-2011, LAMP/EPFL

我在这里尝试深层大小写匹配构造:http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html,代码如下match-deep.scala

class Role
case object Manager extends Role
case object Developer extends Role

case class Person(name:String, age: Int, role: Role)

val alice = new Person("Alice", 25, Developer)
val bob = new Person("Bob", 32, Manager)
val charlie = new Person("Charlie", 32, Developer)

for( person <- List(alice, bob, charlie) ) {
  person match {
    case (id, p @ Person(_, _, Manager)) => println("%s is overpaid".format(p))
    case (id, p @ Person(_, _, _)) => println("%s is underpaid".format(p))
  }
}

我收到以下错误:

match-deep.scala:13: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: this.Person
    case (id, p @ Person(_, _, Manager)) => println("%s is overpaid".format(p))
         ^
match-deep.scala:13: error: not found: value p
    case (id, p @ Person(_, _, Manager)) => println("%s is overpaid".format(p))
                                                                            ^
match-deep.scala:14: error: constructor cannot be instantiated to expected type;
 found   : (T1, T2)
 required: this.Person
    case (id, p @ Person(_, _, _)) => println("%s is underpaid".format(p))
         ^
match-deep.scala:14: error: not found: value p
    case (id, p @ Person(_, _, _)) => println("%s is underpaid".format(p))

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

错误信息清晰

for( person <- List(alice, bob, charlie) ) {
  person match {
    case p @ Person(_, _, Manager) => println("%s is overpaid".format(p.toString))
    case p @ Person(_, _, _) => println("%s is underpaid".format(p.toString))
  }
}

这是做同样事情的简短方法:

for(p @ Person(_, _, role) <- List(alice, bob, charlie) ) {
  if(role == Manager) println("%s is overpaid".format(p.toString))
  else println("%s is underpaid".format(p.toString))
}

修改 我不确定你想要id的真正含义是什么,我想它是列表中人物的index。我们走了:

scala> for((p@Person(_,_,role), id) <- List(alice, bob, charlie).zipWithIndex ) {
     |   if(role == Manager) printf("%dth person is overpaid\n", id)
     |   else printf("Something else\n")
     | }
Something else
1th person is overpaid
Something else

答案 1 :(得分:3)

错误是因为您在person上的匹配不是(id,person)的元组

person match{
  case p @ Person(_, _, Manager)) => println("%s is overpaid".format(p)
  case p : Person => println("%s is underpaid".format(p.toString))
}

这应该足够了。

修改

您可以对此进行调整,以便轻松使用foreach

List(alice, bob, charlie) foreach {
    case p@Person(_,_,Manager)=>println("%s is overpaid".format(p);
    case p:Person =>println("%s is underpaid".format(p.toString)) 
}