How to get a reference to a string in Scala and modify the original string by modifying this reference?

StackOverflow https://stackoverflow.com/questions/15598340

  •  29-03-2022
  •  | 
  •  

문제

As I understand, strings in Scala are value types:

var a = "hello"
var b = a
b = "hi"

-

println(a)   // hello
println(b)  // hi

I want a to point to b and make code above print

hi
hi

Is this possible?

도움이 되었습니까?

해결책

Warning: This is very bad functional style

Your a and b are strings. What you want is a reference to a string!

class StringRef(var s:String)  

val a = new StringRef("hello")
val b = a
b.s = "Hi"
println(a.s)   // Hi
println(b.s)   // Hi

다른 팁

You can't do this because in Java/Scala everything is assigned-by-value. You can't assign a variable to directly reference another variable.

Instead you can assign both variables to contain the same reference value to a mutable object.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top