How Scala List take() method can change a val type?

235 Views Asked by At

I just found a strange behavior with take() method in a String.

Here is my code:

val ji = Array("134","231","2321")
var t = ji
var i = ji(1).take(2)
i = i + 8
t(1)= i
println(ji.mkString(",")) //134,238,2321
println(t.mkString(","))  //134,238,2321

I expected that ji kept its value but it seems affected as well as t. I would like to create a new ji then change into t without touching ji. However, I don't want to make ji redundant.

1

There are 1 best solutions below

0
Dima On

val ji = Array("134","231","2321") - Ok, ji is an array of strings.

var t = ji -- Don't need this. AVOID using vars

var i = ji(1).take(2) -- Don't need this either

i = i + 8 - AVOID mutability. Also, i is a String and 8 is an integer. DON'T do this.

The two lines above should be rewritten as val i = ji(1).take(2) + "8"

t(1)= i -- You are changing the array element here (as written, t and ji are the same array). DON'T do this.

Bottom line:

   val ji = Array("134","231","2321")
   val t = ji.updated(1, ji(1).take(2) + "8")

This does what you want: ji and t are two arrays, that differ in their second element.