Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Enforce compile error on type alias mismatch

Is there a way to get compile time error (or at least warning) when assigning different type aliases that share the same underlying type?

In other words, say I have this code:

type Address = String
type City = String

def foo(x:Address) = ...

I want to get a compile time error/warning if I do:

val city: City = "Dublin"
foo(city)

As far as I can tell, the compiler allows it because they are the same underlying type.

like image 545
Diego Martinoia Avatar asked Nov 03 '14 12:11

Diego Martinoia


1 Answers

To the best of my knowledge, it is not possible to get this "type-safety" you seek for type aliases. However, there is an alternative to type aliases that can be used for what you desire: Value Classes. Basically, a value class can give you a type without allocating a new object. Note that there are some limitations to value classes that you do not have for type aliases.

To quote the scala documentation:

Correctness

Another use case for value classes is to get the type safety of a data type without the runtime allocation overhead. For example, a fragment of a data type that represents a distance might look like:

  class Meter(val value: Double) extends AnyVal {
    def +(m: Meter): Meter = new Meter(value + m.value)
  }

Code that adds two distances, such as

  val x = new Meter(3.4)
  val y = new Meter(4.3)
  val z = x + y

will not actually allocate any Meter instances, but will only use primitive doubles at runtime.

like image 157
Kulu Limpa Avatar answered Sep 18 '22 23:09

Kulu Limpa