0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaのfor文

Last updated at Posted at 2019-10-16

今日は晴れなので初投稿です。
for文書き方3つ+その他を紹介(自分用)

for (i = 1; i <= 5; i++) Scalaだと

    // 1~5まで繰り返す
    for (x <- 1 to 5) {
      println(x)
    }

for(i = 1; i < 5;i++) Scalaだと

    // 1~4まで繰り返す
    for (x <- 1 until 5) {
      println(x)
    }

for(Int i : リスト)拡張for文 Scalaだと

    // listを作成
    val lists = new ArrayBuffer[Int]
    for (x <- 1 to 5) {
      lists += x
    }

    // 拡張for文
    for (x <- lists) {
      println(x)
    }

その他

for文に条件追加

    // xが2だけ処理を許す
    for (x <- lists; if(x.equals(2))) {
      println(x) //2だけでる
    }

2重for文

    // 2重for文
    // もちろんuntilもifも使えるb
    for (x <- 1 to 5; y <- 1 to 5) {
      println(x, y)
    }

yield

勝手にListなどのコレクションにしてくれるんだね。使い所よぐわがんね

    val stringLists = new ArrayBuffer[String]()
    for (x <- lists) yield {
      stringLists += "x = " + x
    }
    println(stringLists);
    // ArrayBuffer(x = 1, x = 2, x = 3, x = 4, x =5)と出る。

コラム

「<-」 を 「->」と書くとエラーで通らないので注意

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?