I'm having trouble understanding how to create implementations of the following code:
Ad-hoc polymorphism
The third approach in Scala is to provide an implicit conversion or implicit
parameters for the trait.
scala> trait Plus[A] {
def plus(a1: A, a2: A): A
}
defined trait Plus
scala> def plus[A: Plus](a1: A, a2: A): A = implicitly[Plus[A]].plus(a1, a2)
plus: [A](a1: A, a2: A)(implicit evidence$1: Plus[A])A
How can I create a concrete implementation, e.g. to add strings, or integers?
Like this?
scala> implicit object StringPlus extends Plus[String] {
| def plus(a1: String, a2: String) = a1+a2
| }
defined module StringPlus
scala> plus("asd", "zxc")
res1: String = asdzxc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With