A variable declared with val specifies that variable is Immutable. A variable declared with var specifies that variable is Mutable
scala> // 'val' example scala> val no:Int = 0 no: Int = 0 scala> no = 5 <console>:8: error: reassignment to val no = 5 ^ scala> val myArr: Array[String] = new Array(2) myArr: Array[String] = Array(null, null) scala> myArr(0) = "a" scala> myArr res26: Array[String] = Array(a, null) scala> // 'var' scala> var no:Int = 0 no: Int = 0 scala> no = 5 no: Int = 5 scala> // 'val' & 'var' in Constructor Parameters #PS:20 scala> class MyClass(val subject:String, var mark:String) defined class MyClass scala> val myObj = new MyClass("maths", "60") myObj: MyClass = MyClass@75fc1992 scala> myObj.mark = "70" myObj.mark: String = 70 scala> myObj.subject = "Physics" <console>:9: error: reassignment to val myObj.subject = "Physics" ^
No comments:
Post a Comment