gpt4 book ai didi

scala - 如何使用 "implicit"作为 apply() 参数?

转载 作者:行者123 更新时间:2023-12-04 16:55:38 28 4
gpt4 key购买 nike

我想做这个:

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)
}

但是后来我收到了这样的错误消息:
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)

我知道隐式通常应该是第二个参数列表的一部分,但我无法弄清楚如何对其进行编码以使其编译并给出我想要的结果。

说明:我正在尝试创建一个框架,可以在其中定义“函数”对象,该对象可以依赖其他函数来计算它们的值。所有函数都应该只接受一个 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

关于scala - 如何使用 "implicit"作为 apply() 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401635/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com