关于scala扩展和Givens

问题描述 投票:0回答:1

这里我有一些简单的 scala 程序,添加了扩展方法来输入 string 或 int 等类型,我想了解我在这里缺少的内容,以便如果我可以执行 1===1 而不是 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) 
}


除了一些类似的解决方案,比如 scala2 中的隐式解决方案

scala implicit scala-3
1个回答
0
投票

只是充实@mateusz-kubuszok 的评论:

% 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
© www.soinside.com 2019 - 2024. All rights reserved.