1

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?

Alex
  • 34,581
  • 26
  • 91
  • 135
  • The title of your question is confused. Modifying references is separate from modifying values. Furthermore, Scala uses Java's `String` and they are immutable. – Randall Schulz Mar 24 '13 at 16:55

2 Answers2

3

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
corny
  • 7,824
  • 3
  • 14
  • 20
2

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.

Community
  • 1
  • 1
Garrett Hall
  • 29,524
  • 10
  • 61
  • 76