ncelik ncelik - 5 months ago 44
Scala Question

Ways of aliasing in scala?

I am trying to figure out if Scala programming language has a way of Aliasing(presence of two or more distinct referencing methods for the same memory location).

I can see example of type aliasing such as "x: (Int, String) = (1,one)". So x has two different types but do they share same memory?

I would greatly appreciate if anyone could give more explanation.


If you want one "variable" to track another, you could do something like this.

scala> var x = 5  // create a variable
x: Int = 5

scala> def y = x  // keep track of x
y: Int

scala> x = 9      // change x
x: Int = 9

scala> y          // yep, y changes too
res1: Int = 9

This isn't a true alias. You can't modify y and see the change in x. A def is simply re-evaluated every time it is invoked, so every time you query y, it re-examines x for the current value.

Note that this type of thing is not considered good Scala practice. In Functional Programming you want to avoid data structures that maintain state, i.e. don't use a var if you don't have to, and good Scala programmers almost never have to.