jcm
jcm

Reputation: 5659

Ad hoc polymorphism in 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?

Upvotes: 5

Views: 312

Answers (3)

Eugene Loy
Eugene Loy

Reputation: 12416

For your example implementation of Plus[Int] would be something like:

scala> implicit val intPlus = new Plus[Int] { def plus(a1: Int, a2: Int):Int = a1 + a2 }
intPlus: Plus[Int] = $anon$1@42674853

... and you then use it:

scala> plus(1, 2)
res1: Int = 3

Upvotes: 1

serejja
serejja

Reputation: 23841

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

Upvotes: 1

Johan S
Johan S

Reputation: 3591

If you allow me to change your syntax a bit, and change your operator (since + is already defined on e.g. Strings):

trait Default[A] {

    def default(a: A): A

}

implicit def stringToDefault(s: String) = new Default[String] {

    def default(other: String) = ""

}

val s = "Hello"
val other = "Goodbye"

val res = s.default(other) // res = ""

Is this what you were looking for? Now we have successfully added a new method to the class String without modifying it, and if you change your type to for example a custom implementation of complex numbers, your Plus trait can be used.

Upvotes: 0

Related Questions