加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 如何使用“implicit”作为apply()参数?

发布时间:2020-12-16 18:37:50 所属栏目:安全 来源:网络整理
导读:我想做这个: 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(imp
我想做这个:

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)

我理解implicits通常应该是第二个参数列表的一部分,但我无法弄清楚如何编码它以便编译,并给出我想要的结果.

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

解决方法

您确定需要依赖扩展功能吗?因为如果你不这样做,只需将扩展的Function1 [Context,T]部分保留下来,你的代码就可以了.

如果你真的需要扩展一个功能而不是我不知道你的情况下的解决方案.但有些情况下您可以尝试重载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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读