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?

Scalaの制御構文

Posted at

文と式の違い

文と式の違いは評価すると値になるか、ならないかが異なる

文はその部分を評価しても値にならない

val value = 2

式はその部分を評価すると値になる

value1 == value2

if式

式なので値を返す
三項演算子として利用することがある

val number = 2
val result = if (number % 2 == 0) "even" else "odd"
println(result)
// output
even

elseを抜くと値を返さないようになる

val number = 2
val result = if (number % 2 == 0) "even"
println(result)
// output
()

match式

他のプログラミング言語のswitchscalaではmatchを使用する
式なので値を返す

val station = "kasumigaseki"

val subway = station match {
  case "kasumigaseki" => "hibiya, chiyoda, marunouchi lines"
  case "uchisaiwaicho" => "mita line"
  case _ => "no match"
}

println(subway) 
// output
hibiya, chiyoda, marunouchi lines

型の判定もできる

val anyValue = 1234

val result = anyValue match {
  case s: String => "String"
  case n: Int => "Int"
  case d: Double => "Double"
  case _ => "No Match"
}

println(result)
// output
Int

case中にif式を挟むこともできる

val address = "taitoward-minowa-xxxx"

val result = address match {
  case value if address.startsWith("taitoward") => "台東区"
  case value if address.startsWith("minatoward") => "港区"
  case _ => "No Match"
} 

println(result)
// output
台東区

for式

基本的な書き方

for (i <- 1 to 3) println(i)
// output
1
2
3

untilにすると最後を含めないようにできる

for (i <- 1 until 3) println(i)
// output
1
2

増加率はbyで変更することができる

for (i <- 1 to 10 by 2) println(i)
// output
1
3
5
7
9

配列、Mapの繰り返し

val array1 = Array(1, 2, 3, 4)
for (i <- array1) println(i)
// output
1
2
3
4
val map1 = Map(1 => "banana", 2 => "orange", 3 => "apple")
for ((k, v) <- map1) println(s"$k, $v")
// output
1, banana
2, orange
3, apple

繰り返し中での条件分岐

val addresses = Array("tokyo, minato, nishishinbashi", "tokyo, taito, minowa", "tokyo, shibuya, dougenzaka")

for(address <- addresses if (address.startsWith("tokyo, minato")) println(address)

// output
tokyo, minato, nishishinbashi

二重for文

for (x <- 1 to 3;y <- 1 to 3) println(s"$x, $y")
// output
1, 1
1, 2
1, 3
2, 1
2, 2
2, 3
3, 1
3, 2
3, 3

while式

var num = 0
while(num <= 3){
  println(num)
  num += 1
}
// output
0
1
2
3

breakcontinueは構文として用意されていない

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?