2013-02-21 45 views
4

我使用Scala的版本:Scala code runner version 2.9.2-unknown-unknown -- Copyright 2002-2011, LAMP/EPFL構造函數不能實例化爲預期類型; 2P @人

我試圖深的情況下匹配從這裏構造: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)) 

我在這裏做錯了什麼?

+0

任何想法是將 'ID' 的case語句的目的是什麼?也許它與舊的Scala語法有關? – tuxdna 2013-02-25 07:47:27

回答

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(([email protected](_,_,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 
+0

你好,Eastsun!感謝您的回答:)請在上面發佈的問題中查看我的評論? – tuxdna 2013-02-25 07:48:58

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 [email protected](_,_,Manager)=>println("%s is overpaid".format(p); 
    case p:Person =>println("%s is underpaid".format(p.toString)) 
} 
+0

你好korefn!謝謝你的回答。這真的有幫助:) – tuxdna 2013-02-25 07:50:42

+0

歡迎您@tuxdna – korefn 2013-02-25 09:51:41

相關問題