Scala-3.控制结构-for

for和foreach语句

for循环

scala> for (i <- 1 to 5) println(i)
1
2
3
4
5

for循环中返回值

用yeild/for组合

scala> val evens = for ( i <- 1 to 5) yield i * 2
evens: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

for循环计数器

scala> val a = Array("Apple", "banana")
scala> for( i <- 0 until a.length){ println(s"$i is ${a(i)}") }
0 is Apple
1 is banana

zipWithIndex:

scala> for((e, count) <- a.zipWithIndex) {
     | println(s"$count is $e")
     | }
0 is Apple
1 is banana

foreach

scala> a.foreach(println)
Apple
banana

scala> a.foreach(e => println(e.toUpperCase))
APPLE
BANANA

多行实现的:

scala> a.foreach{ e => 
     | val s = e.toUpperCase
   def toUpperCase(): String   def toUpperCase(x$1: java.util.Locale): String
     | val s = e.toUpperCase
     | println(s)
     | }
APPLE
BANANA

for循环中的多个计数器

如果遇到了多维数组的情况

scala> for (i <- 1 to 2 ; j <- 1 to 2) println(s"i = $i, j = $j")
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2

也可以:

scala> for{
     | i <- 1 to 2
     | j <- 1 to 2
     | } println(s"i = $i, j = $j")
i = 1, j = 1
i = 1, j = 2
i = 2, j = 1
i = 2, j = 2

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券