Let there are classes Fruit
, Orange
, and Apple
.
abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit
Now I want to add write
functionality to both types Orange
and Apple
. Using the type class pattern I can do the following:
trait Writer[T] {def write(t:T)}
implicit object AppleWriter extends Writer[Apple] {
def write(a:Apple) {println("I am an apple!")}
}
implicit object OrangeWriter extends Writer[Orange] {
def write(o:Orange) {println("I am an orange!")}
}
def write[T](t:T)(implicit w:Writer[T]){w.write(t)}
So for, so good but what if I want to define writeFruits
?
def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}
I would like writeFruits
to call either write[Apple]
or write[Orange]
for each fruit
. I see that it does not work (and I know why) but maybe I can implement the writeFruits
anyway.
Can I implement writeFruits
somehow ?