Ich habe eine Liste von Tupeln, und ich möchte durchqueren und den Wert jedes Elements erhalten.Scala Neuling Probleme mit Tupeln und Verschlüsse
Dies ist der Code:
scala> val myTuples = Seq((1, "name1"), (2, "name2"))
myTuples: Seq[(Int, java.lang.String)] = List((1,name1), (2,name2))
scala> myTuples.map{ println _ }
(1,name1)
(2,name2)
res32: Seq[Unit] = List((),())
So weit, so gut, aber
scala> myTuples.map{ println _._1 }
<console>:1: error: ';' expected but '.' found.
myTuples.map{ println _._1 }
ich auch versucht, mit:
scala> myTuples.map{ println(_._1) }
<console>:35: error: missing parameter type for expanded function ((x$1) => x$1._1)
myTuples.map{ println(_._1) }
scala> myTuples.map{ val (id, name) = _ }
<console>:1: error: unbound placeholder parameter
myTuples.map{ val (id, name) = _ }
scala> myTuples.map{ x => println x }
<console>:35: error: type mismatch;
found : Unit
required: ?{val x: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method any2Ensuring in object Predef of type [A](x: A)Ensuring[A]
and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
are possible conversion functions from Unit to ?{val x: ?}
myTuples.map{ x => println x }
die Variable deklarieren, und die Verwendung von Klammern haben der Trick, aber ich würde gerne wissen, warum die anderen Optionen nicht funktionierten
diese funktionierte gut
myTuples.map{ x => println("id: %s, name: %s".format(x._1, x._2)) }
scala> myTuples.map{ x => println("id: %s, name: %s".format(x._1, x._2)) }
id: 1, name: name1
id: 2, name: name2
res21: Seq[Unit] = List((),())
scala> myTuples.map{ x => val(id, name) = x; println("id: %s, name: %s".format(id, name)) }
id: 1, name: name1
id: 2, name: name2
res22: Seq[Unit] = List((),())
scala> myTuples.map{ x => println(x._1) }
Was passiert mit mir, mit meinem ersten Schritte mit scala, das ist ein wenig darauf, Sie bekommen, was Sie wollen, aber Sie sind nicht sicher, warum Sie die ersten Optionen nicht versucht haben Arbeit ...
FWIW, 'map' verwendet, wenn Sie den Inhalt einer Sammlung verwandeln möchten. Da Ihnen die Ergebnisse egal sind, ist 'foreach' die bevorzugte Methode. – leedm777
netter Tipp, und es macht auch viel deutlicher die Absicht des Entwicklers – opensas