Wednesday, 15 August 2012

scala - Constructor cannot be instantiated to expected type; p @ Person -



scala - Constructor cannot be instantiated to expected type; p @ Person -

i using scala version : scala code runner version 2.9.2-unknown-unknown -- copyright 2002-2011, lamp/epfl

i trying deep case matching build here: http://ofps.oreilly.com/titles/9780596155957/roundingouttheessentials.html , code follows 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 overpaid".format(p)) case (id, p @ person(_, _, _)) => println("%s underpaid".format(p)) } }

i getting next errors:

match-deep.scala:13: error: constructor cannot instantiated expected type; found : (t1, t2) required: this.person case (id, p @ person(_, _, manager)) => println("%s overpaid".format(p)) ^ match-deep.scala:13: error: not found: value p case (id, p @ person(_, _, manager)) => println("%s overpaid".format(p)) ^ match-deep.scala:14: error: constructor cannot instantiated expected type; found : (t1, t2) required: this.person case (id, p @ person(_, _, _)) => println("%s underpaid".format(p)) ^ match-deep.scala:14: error: not found: value p case (id, p @ person(_, _, _)) => println("%s underpaid".format(p))

what doing wrong here?

the error info clear

for( person <- list(alice, bob, charlie) ) { person match { case p @ person(_, _, manager) => println("%s overpaid".format(p.tostring)) case p @ person(_, _, _) => println("%s underpaid".format(p.tostring)) } }

here short way same thing:

for(p @ person(_, _, role) <- list(alice, bob, charlie) ) { if(role == manager) println("%s overpaid".format(p.tostring)) else println("%s underpaid".format(p.tostring)) }

edit not sure real mean of id wanted, suppose index of person in list. here go:

scala> for((p@person(_,_,role), id) <- list(alice, bob, charlie).zipwithindex ) { | if(role == manager) printf("%dth person overpaid\n", id) | else printf("something else\n") | } else 1th person overpaid else

scala scala-2.9

No comments:

Post a Comment