scala構文

変数

1
2
3
4
5
6
7
8
9
10
11
12
object MyApp{
 
  def main(args: Array[String]): Unit = {
   // 変数
   // - val:値の再代入ができない
   // - var:値の再代入ができる
 
   // val msg: String = "hello world";
   val msg = "hello world again"
    println(msg)
  }
}

データ型

1
2
3
4
5
6
7
8
9
10
// 整数 Byte Short Int Long
   val i = 5
   val l = 5555555555L
   val d = 32534.4
   val f = 234.34F
   val c = 'a' // 文字char
   val s = "Hello" // 文字列string
   var flag = true // Boolean
   val msg = "hello\n world again\t"
    println(msg)

四則演算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// + - * / %
val x = 10
println(x / 3)
println(x / 3.0)
println(x % 3)
 
var y = 6
y += 10
println(y)
 
var s = "hello"
println(s + "world")
 
var flag = true
println(!flag)

文字列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
object MyApp{
 
  def main(args: Array[String]): Unit = {
   var name = "igarashi"
   var score = 55
   val height = 159.32
 
   println(s"name: $name, score: $score, height: $height")
   println(s"name: $name, score: ${score + 10}, height: $height")
 
   println(f"name: $name%s, score: $score%d, height: $height%f")
   println(s"name: $name%10s, score: $score%10d, height: $height%10f")
  }
}

条件分岐

1
2
3
4
5
6
7
8
9
object MyApp{
 
  def main(args: Array[String]): Unit = {
   val score = 85
   if (score > 80) println("Great!")
   else if (score > 60) println("Great!")
   else println("soso...")
  }
}

条件分岐 match

1
2
3
4
5
6
7
8
9
10
11
12
13
object MyApp{
 
  def main(args: Array[String]): Unit = {
   val signal = "red"
   var result = signal match {
    case "red" => "stop"
    case "blue" | "green" => "go"
    case "yellow" => "caution"
    case _ => "wrong signal"
   }
   println(result)
  }
}

while

object MyApp{

  def main(args: Array[String]): Unit = {
   var i = 0
   while (i < 10){
   println(i)
   i += 1
   }
  }
}