LoginSignup
1

More than 5 years have passed since last update.

Scalaのvar, valの違い

Last updated at Posted at 2019-01-20

Scalaの変数定義である、varとval、2つのそれぞれの挙動の違いとどちらを使用するべきかに調べたので、メモします。

var

こちらは、C++, javaの通常変数と同じで、値の変更が可能な変数です。
ただし、型の違う値を代入しようとするとエラーとなります。

実行例:

scala> var a = 2
a: Int = 2

scala> // 変数の値は、valueを変更可能
scala> a = 3
a: Int = 3

scala> // 違う型の値を代入すると、エラーになる。
scala> a = 2.5
<console>:12: error: type mismatch;
 found   : Double(2.5)
 required: Int
       a = 2.5

val

こちらは、C++のconst, javaのfinalと同じようなものと考えます。
最初に定義した変数の値の変更が不可能です。
もちろん、型の違う値を代入してもエラーになります。

実行例:

scala> val a = 2
a: Int = 2

scala> // 変数の値は、valueを変更不可能
scala> a = 3
<console>:12: error: reassignment to val
       a = 3
         ^
scala> // 違う型の値を代入すると、エラーになる。
scala> a = 2.5
<console>:12: error: reassignment to val
       a = 2.5
         ^

どちら使うべき?

以下の記事によると一般的にScalaではvalを使うことのほうが多いようです。
https://dwango.github.io/scala_text/basic.html#%E5%A4%89%E6%95%B0%E3%81%AE%E5%9F%BA%E6%9C%AC

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
1