Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
Scala /
for comprehension
It is similar to Python's list comprehensions. scala> for (i <- 1 to 10) yield 2 * i res7: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20) After a yield you provide an expression. However, the value of a block is also an expression, thus you can create more complex comprehensions. For instance, uppercase every 2nd letter of a string: scala> val s = "scala" s: String = scala scala> for (i <- s.indices) yield { | if (i % 2 == 0) s(i).toString.toUpperCase // s(i) is a Char, and a Char has no toUpperCase method | else s(i).toString // let all elements in the result be strings | } res11: scala.collection.immutable.IndexedSeq[String] = Vector(S, c, A, l, A) Transforming an Array / ArrayBuffer / etc.scala> val a = Array(20, 5, 4) a: Array[Int] = Array(20, 5, 4) scala> val res = for (e <- a) yield 2 * e res: Array[Int] = Array(40, 10, 8) The for comprehension creates a new collection whose type is the same as the original collection's type (that you iterate over). |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |