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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With