constructor - How to create custom assignment operator in Scala -


i'm trying create custom data type behaves int, has specific behavior , typing (eg., has positive, has fit within range of our database's 'integer' type, etc).

to make friendly class, want have custom assignment operators, etc., instance i'd following work:

val g: gpid = 1   // create gpid type value 1 val g: gpid = 1l  // take assignment long (and downcast int) if (g == 1) ...   // test value of gpid type against int(1) 

this have far i'm not getting expected behavior:

case class gpid(value: int) extends mappedto[int] {     require(value >= 1, "gpid must positive number")     require(value <= gpdatatypes.integer._2, s"gpid upper bound ${gpdatatypes.integer._2}")      def this(l: long) = this(l.toint)      def gpid = value     def gpid_=(i: int) = new gpid(i)     def gpid_=(l: long) = new gpid(l.toint)      override def tostring: string = value.tostring      override def hashcode:int = value      override def equals(that: any): boolean =         match {             case that: int => this.hashcode == that.hashcode             case that: long => this.hashcode == that.hashcode             case _ => false         } }  object gpid {     implicit val writesgpid = new writes[gpid] {         def writes(g: gpid): jsvalue = {             json.obj(                 "gpid" -> g.value             )         }     }      implicit val reads: reads[gpid] = (         (__ \ "gpid").read[gpid]         )      def apply(l: long) = new gpid(l.toint)      implicit def gpid2int(g: gpid): int = hashcode      implicit def gpid2long(g: gpid): long = hashcode.tolong } 

the problems have are:

  1. assignment doesn't work, instance: val g: gpid = 1

  2. implicit conversion not working, instance: val i: int = g

any appreciated... haven't build custom type before overriding assignment , implicit conversion new me...

object testint extends app {    class gpid(val value: int) {     require(value >= 1, "gpid must positive number")     require(value <= 10, s"gpid upper bound 10")      override def equals(that: any) = value.equals(that)      override def tostring = value.tostring      // add more methods here (pimp library)   }    implicit def fromint(value: int) = new gpid(value)    implicit def fromint(value: long) = new gpid(value.toint) //possible loss of precision    val g: gpid = 1   val g2: gpid = 1l    if (g == 1)     println("one: " + g)   else     println("not one: " + g) } 

prints:

one: 1 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -