Noe*_*oel 28 scala list 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.
Run Code Online (Sandbox Code Playgroud)
使用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...
Run Code Online (Sandbox Code Playgroud)
和更简单的模式匹配方法:
> 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 = ()
Run Code Online (Sandbox Code Playgroud)
par*_*tic 39
第一次尝试是相当不错的.你只是忘了在lambda函数参数周围使用括号.代替:
List("foo","bar").map(x:String => telecom(x,0,0)):List[telecom]
Run Code Online (Sandbox Code Playgroud)
你应该使用:
List("foo","bar").map( (x:String) => telecom(x,0,0)):List[telecom]
Run Code Online (Sandbox Code Playgroud)
或者更简单:
List("foo","bar").map( x => telecom(x,0,0))
Run Code Online (Sandbox Code Playgroud)
Dan*_*ral 28
为了胜人一筹,我必须说它可以进一步减少
List("foo","bar").map(telecom(_,0,0))
Run Code Online (Sandbox Code Playgroud)