LoginSignup
7
2

More than 5 years have passed since last update.

Scalaで条件分岐を使う

Posted at

はじめに

Scalaを勉強し始めたので、学んだ内容を整理していきます。
参考書として 基礎からわかるScala を使っています。

今回は、「条件分岐」について学びました。

1. if式

書き方

if (条件式) { 任意の処理 }
else if (条件式) { 任意の処理 }
else { 任意の処理 }

サンプル

ConditionSample.scala
for(cnt <- 1 to 4) {
  if(cnt == 1){
    println("Nice to meet you.");
  }
  else if(cnt == 2){
    println("Hello");
  }
  else {
    println("Bye...");
  }
}

出力結果

Nice to meet you.
Hello
Bye...
Bye...

2. if式 (三項演算子的な使い方)

書き方

val 不定変数 = if (条件式) 値 else if (条件式) 値 else (条件式) 値;

サンプル

ConditionSample.scala
val name = if (true) "Tom" else "Fred";
println("My name is " + name);

出力結果

My name is Tom

3. match式

書き方

検査値 match { case 値 => 処理; case 値 => 処理; case _ => 処理; }

サンプル

ConditionSample.scala
for(cnt <- 1 to 4) {
  cnt match {
    case 1 => println("Nice to meet you.");
    case 2 => println("Hello");
    case _ => println("Bye...");
  }
}

出力結果

Nice to meet you.
Hello
Bye...
Bye...

7
2
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
7
2