How to force Scala to not use origin of type aliases? -
i created type mystring = string.
now want function accept mystring, not string, latter should not compile @ all.
def myfunc(s: mystring) = println(s) accepts both string , mystring args:
scala> type mystring = string defined type alias mystring scala> def myfunc(s: mystring) = println(s) myfunc: (s: mystring)unit scala> val s1: mystring = "aaa" s1: mystring = aaa scala> myfunc(s1) aaa scala> val s2: string = "aaa" s2: string = aaa scala> myfunc(s2) aaa scala> trait mystring extends string <console>:10: error: illegal inheritance final class string trait mystring extends string ^ scala> s1 res7: mystring = aaa scala> s2 res8: string = aaa scala> s1 == s2 res9: boolean = true
with
type mystring = string you stating type mystring is string, useable (largely) interchangeably within scope both defined.
to enforce usage of mystring on string, can define wrapper class instead:
case class mystring(value: string) extends anyval note: extending anyval prevents class being instantiated @ runtime - see value classes more info.
you restriction on function parameter values want way, although come @ cost of needing explicitly instantiate instances of new type:
scala> val s1: mystring = mystring("aaa") s1: mystring = aaa scala> myfunc(s1) aaa scala> val s2: string = "aaa" s2: string = aaa scala> myfunc(s2) <console>:12: error: type mismatch; found : string required: mystring myfunc(s2) ^
Comments
Post a Comment