带有超载方法和lambda参数的隐式类
我正在尝试以多种友好的方式包装图书馆的Java API。因此,基本API看起来像这样:
trait Keyer[K]
class Base[T] {
def keyBy[K](keyer: Keyer[K]): Base[K] = ???
}
我们要添加lambda方法,因此我们不需要编写new Keyer [K] {def ??? }
始终。扩展基类工作:
class Child[T] extends Base[T] {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Child[Int].keyBy(x => x) // no issues so far
但是使用隐式类做类似的事情失败:
trait ChildOps[T] {
def keyBy[K](fun: T => K): Base[K] = ???
}
implicit class BaseOps[T](base: Base[T]) extends ChildOps[T]
new Base[Int].keyBy(x => x) // compile error: missing parameter type
我还尝试将keyby
方法直接移动到隐式类而没有扩展任何内容,但是编译错误仍然存在:
implicit class BaseOps2[T](base: Base[T]) {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Base[Int].keyBy(x => x) // compile error: missing parameter type
放弃和注释使用类型的方法
方法也是有问题的:
implicit class BaseOps2[T](base: Base[T]) {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Base[Int].keyBy[Int]((x: Int) => x)
// type mismatch;
// found : Int => Int
// required: com.test.ImplicitTest.Keyer[Int]
// new Base[Int].keyBy[Int]((x: Int) => x)
因此,问题是:如何在隐式类中添加使用lambda参数的通用覆盖方法?为什么我上面的所有尝试都会给出编译错误?
代码在Scala 2.13.8和2.12.15上失败,但在3.1.2上成功编译。
I'm trying to wrap a Java API of a library in multiple Scala-friendly ways. So the base API looks like this:
trait Keyer[K]
class Base[T] {
def keyBy[K](keyer: Keyer[K]): Base[K] = ???
}
We want to add a lambda method, so we don't need to write new Keyer[K] { def ??? }
all the time. Extending the base class works:
class Child[T] extends Base[T] {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Child[Int].keyBy(x => x) // no issues so far
But doing similar thing using implicit classes fails:
trait ChildOps[T] {
def keyBy[K](fun: T => K): Base[K] = ???
}
implicit class BaseOps[T](base: Base[T]) extends ChildOps[T]
new Base[Int].keyBy(x => x) // compile error: missing parameter type
I also tried to move the keyBy
method directly to the implicit class without extending anything, but the compile error is still there:
implicit class BaseOps2[T](base: Base[T]) {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Base[Int].keyBy(x => x) // compile error: missing parameter type
Giving up and annotating keyBy
method with types is also problematic:
implicit class BaseOps2[T](base: Base[T]) {
def keyBy[K](fun: T => K): Base[K] = ???
}
new Base[Int].keyBy[Int]((x: Int) => x)
// type mismatch;
// found : Int => Int
// required: com.test.ImplicitTest.Keyer[Int]
// new Base[Int].keyBy[Int]((x: Int) => x)
So the question is: how can I add a generic overridden method with lambda parameter in an implicit class? And why all my attempts above giving a compile errors?
Code fails on Scala 2.13.8 and 2.12.15, but compiles successfully on 3.1.2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论