web-dev-qa-db-fra.com

Convert Scala liste à la liste avec un autre type

Je souhaite créer une liste de types d'objets plus complexes à partir d'une liste de types simples. Par exemple, List[String] => List[MyType].

Je l'ai donné trois va à l'aide d'approches basées sur la carte. Une carte simple avec Wildcard:

> 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.

Une méthode de correspondance de modèle utilisant le constructeur de la classe de cas:

> 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...

et une méthode de correspondance de modèle plus simple:

> 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 = ()
28
Noel

Le premier essai est tout à fait ok. Vous avez juste oublié d'utiliser des parenthèses autour des arguments de la fonction Lambda. À la place de:

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

tu devrais utiliser:

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

ou plus simple:

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

Ou vous pouvez faire ça:

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