Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ad hoc polymorphism in Scala

Tags:

scala

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 image 617
jcm Avatar asked Nov 01 '22 12:11

jcm


1 Answers

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
like image 148
serejja Avatar answered Nov 11 '22 06:11

serejja