Why val array makes no error while I assign something in some array position? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why val array makes no error while I assign something in some array position?

I declared an array and assign 3 elements using val keyword. So I thought I cannot change any element in the array. But I could! Why it works? But when I assign a new array as a whole, then I got compiler error saying something like this - val cannot be assigned again. Why does this happen? Please see my code below to understand: https://code.sololearn.com/cNn9QTwPx8hN/?ref=app Sorry for my bad English.

14th Aug 2021, 12:34 PM
Jakariya
Jakariya - avatar
3 Answers
+ 4
Have a look at following stackoverflow question, https://www.google.com/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/50466863/kotlin-val-cannot-be-reassigned-but-can-be-reassigned-by-accessing-from-inde&ved=2ahUKEwiM2J2Bx7DyAhXHZSsKHQXnANAQFnoECCEQAQ&usg=AOvVaw12su001bDZJ-s6mKXx5kM3 From what i understand, you can't change the reference to new object when using val but you can change the reference of the object inside that object (referring to int objects inside array). I might be wrong .
14th Aug 2021, 1:16 PM
Abhay
Abhay - avatar
+ 6
https://code.sololearn.com/c8at0IMeB07Y/?ref=app I'm agree with Abhay ,see this code that how can you change element using val
14th Aug 2021, 1:28 PM
Abhiyantā
Abhiyantā - avatar
+ 2
Thanks Rishav and Abhay. I'm beginner in Kotlin, but I understood this.
14th Aug 2021, 1:59 PM
Jakariya
Jakariya - avatar