Typed primitives in Scala 2.11 -


as see, primitive types string , long cannot extended defined final. pity type-safe approach. in code does not revolve around e.g. string manipulation, prefer type data rather use string, long, int, etc: long i'm using type safe language, i'd code typed ground up.

as per experimentation , as demonstrated on old question type aliases not seem facilitate this. currently, use things like:

case class domaintype(value: string) 

at cost of having use .value value needed.

is there other language feature been introduced after scala 2.8 or otherwise, can neatly facilitate type safe sub-typed primitives? there object overrides proxy underlying value, still let type matching occur?

i don't agree way of thinking. java primitives can't extended because primitives (btw string not primitive). direct representation of byte code types. extending them make no sense compiler perspective.

implicit value classes

scala deals using pimp library pattern, example class richint. permits add new methods existing type (mainly) without object instantiation (through value classes , implicits). please have implicit classes.

implicit class domaintype(val o: string) extends anyval {   def mydomainmethod: int = o.size }  "hello".mydomainmethod // return 5 

problem, doesn't allow restrict type domaintype. type classes can you.

type classes

here want add constraint type, without inheritance. said in this link,

as such, type classes allow ad-hoc , retroactive polymorphism. code relies on type classes open extension without need create adapter objects.

the following example shows how method foo accepts argument implicit of type domaintype[t] in scope. replaces inheritance wanted retroactive polymorphism. keep benefits domain type: intent clear, call type safe , can add new domain methods.

trait domaintype[t] {   def mydomainmethod(o: t): int }  object domaintype {   implicit object stringdomaintype extends domaintype[string] {     def mydomainmethod(o: string): int = o.size   } }  def foo[t : domaintype](p: t): int = {   implicitly[domaintype[t]].mydomainmethod(p) }  foo("hello") // return 5 foo(5) // compilation exception 

case classes + implicits

if thing annoys domaintype case class call .value, can add implicit you.

implicit def unwrapdomaintype(o: domaintype): string = o.value 

of course can lower clarity of code , not recommend it.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -