Seb*_*iot 5 scala implicit apply
我想做这个:
abstract class Context {
def getInt(id: Int): Int
}
abstract class Dependency[+T]
(val name: String, val id: Int)
extends Function1[Context,T]
class IntDependency(name: String, id: Int)
extends Dependency[Int](name, id) {
def apply(implicit context: Context): Int =
context.getInt(id)
}
Run Code Online (Sandbox Code Playgroud)
但后来我得到一个这样的错误信息:
class IntDependency needs to be abstract, since method apply in trait
Function1 of type (v1: Context)Long is not defined (Note that T1 does
not match Context)
Run Code Online (Sandbox Code Playgroud)
我理解implicits通常应该是第二个参数列表的一部分,但我无法弄清楚如何编码它以便编译,并给出我想要的结果.
说明:我正在尝试创建一个框架,其中可以定义"Function"对象,该对象可以依赖于其他函数来计算它们的值.所有函数应该只接受一个Context参数.上下文知道其他函数的"结果".函数实例应该是不可变的,状态驻留在上下文中.我希望函数在创建时创建"依赖"字段,隐式获取上下文,并返回该上下文中依赖项的值,以便访问apply方法内部的依赖关系"感觉"访问参数或字段,即没有明确地将上下文作为参数提供给依赖项.
你确定需要Dependency延长Function吗?因为如果你不这样做,只需将extends Function1[Context,T]部分保留下来,你的代码就可以了.
如果你真的需要扩展一个Function我不知道你的情况下的解决方案.但有些情况下您可以尝试重载该apply方法.像这儿:
scala> val sum = new Function1[Int, Function1[Int, Int]] {
| def apply(a: Int) = (b: Int) => a + b
| def apply(a: Int)(implicit b: Int) = a + b
|}
sum: java.lang.Object with (Int) => (Int) => Int{def apply(a:Int)(implicit b: Int): Int} = <function1>
scala> sum(2)(3)
res0: Int = 5
scala> implicit val b = 10
b: Int = 10
scala> sum(2)
res1: Int = 12
Run Code Online (Sandbox Code Playgroud)