在scala中实现函数的实现

时间:2018-01-31 10:13:14

标签: scala functional-programming

我有一个功能

def foo[A](a1: A, a2: A): A = a1|+|a2

需要实现实现

结果必须是:

foo[Test](Test(1), Test(2)) // Test(3)

我在IDEA工作表中编写了一些代码,但它不是编译

case class Test(num: Int)

object Test {
  implicit val test = new Writer[Test] {
    def write(v1: Test, v2: Test) = {
      Test(v1.num + v2.num)
    }
  }
}

trait Writer[A] {
  def write(v1: A, v2: A): A
}


implicit class someT[A](a1: A) {

  def |+|(a2: A)(implicit writer: Writer[A]) = {
    writer.write(a1, a2)
  }
}

def foo[A](a1: A, a2: A): A = a1|+|a2

foo[Test](Test(1), Test(2))

输出错误是:

Error:(32, 34) could not find implicit value for parameter writer: A$A213.this.Writer[A]
def foo[A](a1: A, a2: A): A = a1|+|a2
                            ^
Error:(32, 34) not enough arguments for method |+|: (implicit writer: A$A213.this.Writer[A])A.
Unspecified value parameter writer.
def foo[A](a1: A, a2: A): A = a1|+|a2
                            ^

1 个答案:

答案 0 :(得分:3)

您错过了Writer[A]所需的隐式foo

def foo[A](a1: A, a2: A)(implicit writer: Writer[A])

或者如果你更喜欢上下文界限:

def foo[A : Writer](a1: A, a2: A)

现在,编译器可以反过来看到|+|范围内有Writer[A]