我如何使用“隐式"作为 apply() 参数? [英] How do I use "implicit" as apply() parameter?

查看:27
本文介绍了我如何使用“隐式"作为 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)
}

但随后我收到如下错误消息:

But then I get an error message like this:

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)

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

I understand that implicits should normally be part of the second parameter list, but I can't work out how to code it so it compiles, and gives the result I want.

说明:我正在尝试创建一个框架,可以在其中定义函数"对象,该对象可以依赖其他函数来计算它们的值.所有函数都应该只接受一个 Context 参数.上下文知道其他函数的结果".函数实例应该是不可变的,状态驻留在上下文中.我希望函数在创建时创建依赖"字段,它隐式获取上下文,并返回该上下文中依赖的值,以便访问应用方法内部的依赖感觉like"访问参数或字段,即没有明确地将上下文作为参数提供给依赖项.

Explanation: I'm trying to create a framework where one can define "Function" object, which can depend on other functions to compute their value. All functions should only take a single Context parameter. The context know the "result" of the other functions. The function instances should be immutable, with the state residing in the context. I want the functions to create "dependency" fields at creation time, which take the context implicitly, and return the value of the dependency within that context, so that accessing the dependency inside of the apply method "feels like" accessing a parameter or field, that is without explicitly giving the context as parameter to the dependency.

推荐答案

您确定需要 Dependency 来扩展 Function 吗?因为如果你不这样做,只需将 extends Function1[Context,T] 部分留在外面,你的代码就会工作.

Are you sure you need your Dependency to extend a Function? Because if you don't, just leave the extends Function1[Context,T] part out and your code will work.

如果你真的需要扩展一个 Function 而不是我不知道你的情况的解决方案.但在某些情况下,您可以尝试重载 apply 方法.喜欢这里:

If you really need to extend a Function than I don't know of a solution in your case. But there are cases where you could try to overload the apply method. Like here:

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

这篇关于我如何使用“隐式"作为 apply() 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆