LoginSignup
0
0

More than 5 years have passed since last update.

Scalaで変数を使う

Posted at

はじめに

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

今回は、「変数」について学びました。

変数の種類

Scalaで登場する変数は下記の2つ。

  1. val -> 定数。宣言後は値が変わらないもの。
  2. var -> 変数。宣言後も値が変わるもの。

1. val

書き方

val 変数名: 型 = 初期値;

サンプルソース

VariableSample.scala
object VariableSample extends App {
  val valValue: Int = 100;
  printf("定数 = %d \n", valValue);

  //下記の記述をすると、コンパイルエラーが発生
  //valValue += 1;
}

実行結果

定数 = 100

2. var

書き方

var 変数名: 型 = 初期値;

サンプルソース

VariableSample.scala
object VariableSample extends App {
  var varValue: Int = 99;
  printf("変数 = %d \n", varValue);
  varValue += 1;
  printf("変数 = %d \n", varValue);
}

実行結果

変数 = 99
変数 = 100

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