Scala: force compilation error if type aliases do not agree

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

In other words, let's say I have this code:

type Address = String type City = String def foo(x:Address) = ... 

I want to get a temporary compilation error / warning if I do this:

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

As far as I can tell, the compiler admits this because they are the same basic type.

+6
source share
2 answers

As far as I know, it is impossible to get this "type safety" that you are looking for type aliases. However, there is an alternative to the types of aliases that you can use for what you want: Value classes . Basically, a value class can give you a type without allocating a new object. Note that there are some restrictions on value classes that you do not have for type aliases.

To quote the scala documentation:

Correctness

Another use of value classes is to obtain a data type security type without the expense of allocating run time. For example, a data type fragment representing a distance might look like this:

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

Code that adds two distances, for example

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

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

+4
source

No. At least, not without modifying the compiler (perhaps this is possible with the help of a compiler plugin or even a macro), and if you make this change, many popular libraries (including the standard library) and standard code examples will not compile.

You might like to use value classes as described in @Kulu's answer. Alternatively, Scalaz Tagged Types avoid overhead in more situations (for example, putting them in a collection or using subst to safely raise the level of a generic type that uses a tagged type).

+3
source

Source: https://habr.com/ru/post/977650/


All Articles