scala – 无法将构造函数实例化为预期类型; p @ Person
发布时间:2020-12-16 18:55:21 所属栏目:安全 来源:网络整理
导读:我使用 scala版本: Scala代码运行版本2.9.2-未知 – 未知 – 版权所有2002-2011,LAMP / EPFL 我在这里尝试深度大小写匹配构造:http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html,代码如下match-deep.scala: class Rolecase ob
我使用
scala版本:
Scala代码运行版本2.9.2-未知 – 未知 – 版权所有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",Developer) for( person <- List(alice,bob,charlie) ) { person match { case (id,p @ Person(_,_,Manager)) => println("%s is overpaid".format(p)) case (id,_)) => 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,Manager)) => println("%s is overpaid".format(p)) ^ match-deep.scala:13: error: not found: value p case (id,Manager)) => println("%s is overpaid".format(p)) ^ match-deep.scala:14: error: constructor cannot be instantiated to expected type; found : (T1,_)) => println("%s is underpaid".format(p)) ^ match-deep.scala:14: error: not found: value p case (id,_)) => println("%s is underpaid".format(p)) 我在这做错了什么? 解决方法
错误信息很清楚
for( person <- List(alice,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,charlie) ) { if(role == Manager) println("%s is overpaid".format(p.toString)) else println("%s is underpaid".format(p.toString)) } 编辑 scala> for((p@Person(_,role),id) <- List(alice,charlie).zipWithIndex ) { | if(role == Manager) printf("%dth person is overpaidn",id) | else printf("Something elsen") | } Something else 1th person is overpaid Something else (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |