Scala Tutorialsを読む 4 Final Variables

今日は4 Final Variablesを読みます。

http://scalatutorials.com/tour/interactive_tour_of_scala_final_variables.html

Final変数ですな。Swift騒ぎで忘れてたよ orz...

FInal variables are declared using the val keyword Final変数はvalキーワードを使って宣言される。Swiftはvarはvarでvalはletなんだよな。 どっちがいいのだろうって、言ってもまぁ、似たような物だけど。

(a final variable is a variable that can't be reassigned) ファイナル変数は再代入出来ない変数です。

The code on the left looks almost exactly like in the previous step, 左側のコードは前のステップと同じに見えます、 with one small change 1つの小さな変更をすると。

これ悩んでしまったのだけど、左側のコードってのは、

val x = 1 + 2 //val instead of var  
println(x)  
x = 3 * 4 //error: reassignment to val  
println(x)  

このコードの事ね。

The var was changed to val.

varはvalに変更されています。(前のページから、確かに1文字変えただけだ)

Try to run the code on the left, 左のコードで実行してみてください、ってことで実行するとエラーになる。 the compiler should complain on line 3 コンパイルはcomplainをライン3でいうと。complainは苦情とからしい。エラーがでるってことだな。 since we are trying to reassign x which is a val. valなxに再代入しようとしたからだ。

Exercise エクササイズ 練習だよな

Edit the code on the left, 左のコードを編集して、 so it will run. 実行できるようにしてみよう。

(either change the val back to var, valをvarに戻すのではなくて、 remove the reassignment to x or assign the result of the expression in line 3 to a different val or var.

3行目のxへの再代入を消して違うvalかvarの変数にする。)

val x = 1 + 2 //val instead of var  
println(x)  
val x2 = 3 * 4
println(x2)  

とかですな。

val x = 1 + 2 //val instead of var  
println(x)  
val x = 3 * 4
println(x)  

これだとエラーだ。

Note: メモ:

Prefer using 'val' over 'var' valを使ったほうがよりよいです。 (and immutable objects over mutable ones). immutableなオブジェクトがmutableなものよりよいですと。 There are many benefits 色んな利点があります。 that are out of the scope of this small tour. この小さなツアーでは範囲を超えるけど。

ってところですね。