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