Scalaの変数について


はじめに

下記のテキストを通して、基本的な書き方を学んでいきます。
https://dwango.github.io/scala_text/basic.html

CやPHPを使ってきた私には、varval なにそれ!?って状態でしたので、どのような違いがあるか実際に試してみました。

そもそも、 varval はなんの略称?ということで調べてみると

「val」はvalueの略で,valueとは「データや一つのオブジェクト」を指す言葉です。「var」のほうは,普通にvariable(変数)

とのことだそうで。
Source:http://itpro.nikkeibp.co.jp/article/COLUMN/20080708/310424/?rt=nocnt

変数について

  • 試した結論
    • var は値の更新ができ、 val は値の更新ができない
    • 対象となる変数の型以外は挿入不可
    • 同名再定義は不可

値の更新ができるか

  • var
scala> var test_var = 1 + 2
test_var: Int = 3

scala> test_var = 10
test_var: Int = 10
  • val
scala> val test_val = 1 + 2
test_val: Int = 3

scala> test_val = 10
<console>:8: error: reassignment to val
       test_val = 10
                ^

宣言後に別の型を入れてみる

  • var
scala> var test_var = 1 + 2
test_var: Int = 3

scala> test_var = "hoge"
<console>:8: error: type mismatch;
 found   : String("hoge")
 required: Int
       test_var = "hoge"
                  ^
  • val
scala> val test_val = 1 + 2
test_val: Int = 3

scala> test_val = "hoge"
<console>:8: error: reassignment to val
       test_val = "hoge"
                ^

型宣言した上で、別の型を入れてみる

  • 正常系
scala> val test_val: Int = 10
test_val: Int = 10

scala> var test_var: Int = 10
test_var: Int = 10
  • val, varそれぞれ
scala> val test_val: Int = "hoge"
<console>:7: error: type mismatch;
 found   : String("hoge")
 required: Int
       val test_val: Int = "hoge"
                           ^

scala> var test_var: Int = "hoge"
<console>:7: error: type mismatch;
 found   : String("hoge")
 required: Int
       var test_var: Int = "hoge"
                           ^

再定義するとどうなる?

  • 基本的な記述
scala> :paste
// Entering paste mode (ctrl-D to finish)

var test_var = 10
val test_val = 20

// Exiting paste mode, now interpreting.

test_var: Int = 10
test_val: Int = 20
  • var + var
scala> :paste
// Entering paste mode (ctrl-D to finish)

var test_var = 1 + 2
var test_var = 10

// Exiting paste mode, now interpreting.

<console>:8: error: test_var  is already defined as variable test_var
       var test_var = 10
           ^
  • val + val
scala> :paste
// Entering paste mode (ctrl-D to finish)

val test_val = 1 + 2
val test_val = 10

// Exiting paste mode, now interpreting.

<console>:8: error: test_val is already defined as value test_val
       val test_val = 10
           ^
  • val + var
scala> :paste
// Entering paste mode (ctrl-D to finish)

val test = 1 + 2
var test = 10

// Exiting paste mode, now interpreting.

<console>:8: error: test  is already defined as value test
       var test = 10
           ^
  • var + val
scala> :paste
// Entering paste mode (ctrl-D to finish)

var test = 1 + 2
val test = 10

// Exiting paste mode, now interpreting.

<console>:8: error: test  is already defined as variable test
       val test = 10
           ^