1

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.

ncelik
  • 119
  • 9
  • That's not type aliasing but pattern matching. Type aliasing is `type Str = String` which `Str` that can replace any occurence of `String` type. – cchantep Oct 14 '16 at 07:26
  • You have things like `Either`, that allows you to store two kinds of types, for example `val e:Either[Int, Double] = Left(1)`, but as `int` and `double` have different sizes, I do not know if they will be share the same memory. – Alejandro Alcalde Oct 14 '16 at 07:27
  • It rather depends on what you mean by "same memory", but it also really doesn't matter because the whole point of the Scala language (and the JVM itself) is to remove those types of concerns from the programmer. Memory allocation might change from version to version, but that should **not** break any well designed programs. – jwvh Oct 14 '16 at 07:28
  • I think you're looking for a [sum type](https://en.wikipedia.org/wiki/Tagged_union). The best there is today is an `Either[A,B]`, which doesn't share the same memory location for both variables, it's just represents one of the types (`A` or `B`) with algebraic data types. – Yuval Itzchakov Oct 14 '16 at 07:51
  • Possible duplicate of [How to define "type disjunction" (union types)?](http://stackoverflow.com/questions/3508077/how-to-define-type-disjunction-union-types) – Yuval Itzchakov Oct 14 '16 at 07:55

1 Answers1

1

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.

jwvh
  • 50,871
  • 7
  • 38
  • 64