Scala學習之for 迴圈和 yield 的例子

2022-09-15 04:36:14 字數 1637 閱讀 6354

for迴圈中的 yield 會把當前的元素記下來,儲存在集合中,迴圈結束後將返回該集合。scala中for迴圈是有返回值的。如果被迴圈的是map,返回的就是map,被迴圈的是list,返回的就是list,以此類推。

例1:

1 scala> for (i <- 1 to 5) yield i

2 res10: scala.collection.immutable.indexedseq[int] = vector(1, 2, 3, 4, 5)

例2:

1 scala> for (i <- 1 to 5) yield i * 2

2 res11: scala.collection.immutable.indexedseq[int] = vector(2, 4, 6, 8, 10)

例3: for/yield 迴圈的求模操作:

1 scala> for (i <- 1 to 5) yield i % 2

2 res12: scala.collection.immutable.indexedseq[int] = vector(1, 0, 1, 0, 1)

例4:scala 陣列上的 for 迴圈 yield 的例子

1 scala> val a = array(1, 2, 3, 4, 5)

2 a: array[int] = array(1, 2, 3, 4, 5)

34 scala> for (e <-a) yield e

5 res5: array[int] = array(1, 2, 3, 4, 5)

67 scala> for (e <- a) yield e * 2

8 res6: array[int] = array(2, 4, 6, 8, 10)

910 scala> for (e <- a) yield e % 2

11 res7: array[int] = array(1, 0, 1, 0, 1)

例5:for 迴圈, yield, 和守衛( guards) (for loop 'if' conditions)

假如你熟悉了 scala 複雜的語法, 你就會知道可以在 for 迴圈結構中加上 'if' 表示式. 它們作為測試用,通常被認為是乙個守衛,你可以把它們與 yield 語法聯合起來用。參見::

1 scala> val a = array(1, 2, 3, 4, 5)

2 a: array[int] = array(1, 2, 3, 4, 5)

34 scala> for (e <- a if e > 2) yield e

5 res1: array[int] = array(3, 4, 5)

加上了 "if e > 2" 作為守衛條件用以限制得到了只包含了三個元素的陣列.

例6:scala for 迴圈和 yield 的例子 - 總結

如果你熟悉 scala 的 loop 結構, 就會知道在 for 後的圓括號中還可以許更多的事情. 你可以加入 "if" 表示式,或別的語句, 比如下面的例子,可以組合多個 if 語句:

1 def scalafiles =

2for

yield file

yield 關鍵字的簡短總結:

**:感謝作者無私分享!

scala基礎之迴圈 break和continue

for表示式 for i 表示式 集合 陣列 scala val num 1.to 5 num scala.collection.immutable.range.inclusive range 1,2,3,4,5 scala for i num 12 345scala for i 1.to 6 12...

Scala學習(1) for迴圈

to 前後都包含 until和range只包含前,不包含後 迴圈表示式 println 迴圈表示式 val arr 1 to 9 println s to表示式 val arr1 1 until 9 println s until表示式 val arr2 range 1,9,1 println s ...

Scala之入門基礎學習

這裡主要給大家展示scala的基礎,比如for迴圈,函式,陣列以及元組和印射,在 中有注釋。一,for迴圈 object for def foryeild unit 在這裡if就相當於乙個守衛過濾掉一些元素 def forif unit def forhight unit until就是在迴圈的時候...