Here I have some simple scala program with added extension method to type like string or int, I want to understand what I am missing here so that it works if I can do 1===1 instead of 1.toEqops====1.
trait Eq[A] {
def eq(lhs: A, rhs: A): Boolean
}
class EqOps[A](lhs: A)(using eqt: Eq[A]) {
def ====(rhs: A): Boolean = eqt.eq(lhs, rhs)
}
object EqOps {
extension[A](lhs:A)(using e:Eq[A]) {
def toEqOps = new EqOps(lhs)
}
}
object EqInstances {
given equals: Eq[Int] = (lhs: Int, rhs: Int) => lhs == rhs
given equals1: Eq[String] = (lhs: String, rhs: String) => lhs.equals(rhs)
}
def main(): Unit = {
val r1=1.toEqOps====(1)
}
Excepting some similiar solution like implicits in scala2
1
Just fleshing out @mateusz-kubuszok’s comment:
% scala-cli
Welcome to Scala 3.4.2 (17.0.5, Java Java HotSpot(TM) 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala> trait Eq[A] {
| def eq(lhs: A, rhs: A): Boolean
| }
| extension [A:Eq](a : A) def ==== (other : A) : Boolean = summon[Eq[A]].eq(a,other)
// defined trait Eq
def ====[A](a: A)(other: A)(implicit evidence$1: Eq[A]): Boolean
scala> given Eq[String] with
| def eq(lhs: String, rhs: String): Boolean = lhs.equalsIgnoreCase(rhs)
|
// defined object given_Eq_String
scala> "hello" ==== "Hello"
val res0: Boolean = true
scala> "hello" ==== "Jello"
val res1: Boolean = false