Special polymorphism in Scala

I am 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 specific implementation, for example. add strings or integers?

+4
source share
3 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
+1
source

For your example, the implementation Plus[Int]will look something like this:

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

... and then use it:

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

( + , , String s):

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 = ""

, ? String , , , , Plus.

0

All Articles