将Scala List转换为另一种类型的List

时间:2011-06-17 16:49:09

标签: list scala pattern-matching

我想从简单类型List创建一个更复杂的对象类型List。例如,List[String] => List[MyType]

我已经使用基于地图的方法给了它三个。带通配符的简单地图:

> case class telecom (name:String, longitude:Double, latitude:Double)
defined class telecom
> List("foo","bar").map(x:String => telecom(x,0,0)):List[telecom]
:1: error: ';' expected but ')' found.

使用case类构造函数的模式匹配方法:

> def foo(c:List[String]){                                                                              
 | c match {                                                                                             
 | case tc:List[telecom] => tc.map(telecom(_,0,0)):List[telecom]; println("matched telephonecomapny");
 | case _ => println("matched nothing"); throw new ClassCastException(); }}
warning: there were unchecked warnings; re-run with -unchecked for details
foo: (c: List[String])Unit

>  foo(List("foo","bar"))
java.lang.ClassCastException: java.lang.String cannot be cast to usda.rd.broadband.model.DatabaseTables$TelephoneCompany
    at $anonfun$foo$1.apply(<console>:11)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:206)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:206)
    at scala.collection.LinearSeqOptimized$class.foreach(LinearSeqOptimized.scala:61)
    at scala.collection.immutable.List.foreach(List.scala:45)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:206)
    at scala.collection.immutable.List.map(List.scala:45)
    at .foo(<console>:11)
    at .<init>(<console>:11)
    at .<clinit>(<console>)
    at RequestResult$.<init>(<console>:9)
    at RequestResult$.<clinit>(<console>)
    at RequestResult$scala_repl_result(<console...

和更简单的模式匹配方法:

> def bar(c:List[String]){
 | c match {
 | case tc:List[telecom] => tc 
 | case _ => println("matched nothing")}}
 warning: there were unchecked warnings; re-run with -unchecked for details
 foo: (c: List[String])Unit
> val r = bar(List("foo","bar"))
t: Unit = ()

3 个答案:

答案 0 :(得分:37)

第一次尝试很好。你只是忘了在lambda函数参数周围使用括号。而不是:

List("foo","bar").map(x:String => telecom(x,0,0)):List[telecom]

你应该使用:

List("foo","bar").map( (x:String) => telecom(x,0,0)):List[telecom]

或更简单:

List("foo","bar").map( x => telecom(x,0,0))

答案 1 :(得分:26)

为了胜人一筹,我必须说它可以进一步缩小为

List("foo","bar").map(telecom(_,0,0))

答案 2 :(得分:2)

或者你可以做到:

List("foo","bar").map(x => telecom(x,0,0))