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

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

我知道隐式对象通常应该是 second 参数列表的一部分,但是我无法弄清楚如何对其进行编码,以便对其进行编译并提供所需的结果.

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参数.上下文知道其他功能的结果".函数实例应该是不可变的,状态驻留在上下文中.我希望函数在创建时创建依赖项"字段,该字段隐含上下文 ,并在该上下文中返回依赖项的值,以便在apply方法内部访问依赖项感到例如"来访问参数或字段,而无需将上下文作为参数显式地提供给依赖项.

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天全站免登陆