I am new to scala and I am trying to implement a method method "append
" which appends two numbers or string.
The ideato practice on this code came from this post where I was referring an example of append
method and Appendable
trait used for creating implicits
.
I tried to replicate the same code in my IntelliJ using view bound and context bound concepts but somehow it is not working.
Can Anyone please suggest what is missing in below code ? why it is failing ? I also tried to replicate the same here.
trait Appendable[A]{
def append(a: A, b : A) : A
}
object Appendable {
implicit val appendableString = new Appendable[String] {
override def append(a: String, b : String): String = a + b
}
implicit val appendableInt = new Appendable[Int] {
override def append(a: Int, b : Int): Int = a + b
}
}
object ItemAppenderTester extends Object {
def appendItem[A <% Appendable[A]]( a : A, b : A) = a append b
def appendItem2[A : Appendable[A]]( a : A, b : A) = implicitly[Appendable[A]].append(a,b)
def appendItem3(a : A, b : A) (implicit ev : Appendable[A]) = ev.append(a,b)
appendItem(1,2)
}
def appendItem[A <% Appendable[A]]( a : A, b : A)
is now just wrong. X <% Y
means (implicit ev: X => Y)
. You didn't define implicits A => Appendable[A]
(on contrary to the article at Medium, see toAppendable
there). Also <%
is deprecated.
appendItem2
can be fixed:
def appendItem2[A : Appendable]( a : A, b : A)
appendItem3
can be fixed:
def appendItem3[A](a : A, b : A) (implicit ev : Appendable[A])
Actually appendItem2
is desugared into appendItem3
.