typeclass - Question about type classes in Scala -


let there classes fruit, orange, , apple.

abstract class fruit class orange extends fruit class apple extends fruit

now want add write functionality both types orange , apple. using type class pattern can following:

trait writer[t] {def write(t:t)}  implicit object applewriter extends writer[apple] {    def write(a:apple) {println("i apple!")}  }  implicit object orangewriter extends writer[orange] {    def write(o:orange) {println("i orange!")}  }  def write[t](t:t)(implicit w:writer[t]){w.write(t)}

so for, if want define writefruits ?

def writefruits(fruits:list[fruit]) {for (fruit <- fruits) write(fruit)}

i writefruits call either write[apple] or write[orange] each fruit. see not work (and know why) maybe can implement writefruits anyway.

can implement writefruits somehow ?

you need pick out fruit writer exists. unfortunately, once you've cast fruit you've lost ability automatically figure out which. if must set problem way--rather assembling list of writable fruit or somesuch--then 1 reasonable option split out types again fruitwriter:

def writeone[t](t:t)(implicit w:writer[t]){w.write(t)}  // new name avoid shadowing  implicit object fruitwriter extends writer[fruit] {   def write(f: fruit) { f match {     case o: orange => writeone(o)     case a: apple => writeone(a)   }} }  scala> val fruits = list(new apple, new orange) fruits: list[fruit] = list(apple@1148ab5c, orange@39ea2de1)  scala> (fruit <- fruits) writeone(fruit) apple! orange! 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -