Scala如何创建与函数同名的隐式对象
给定以下特征和伴生对象定义:Scala如何创建与函数同名的隐式对象,scala,implicit-conversion,implicit,companion-object,Scala,Implicit Conversion,Implicit,Companion Object,给定以下特征和伴生对象定义: trait Api { def foo(s: String): String } object Api extends Api { override def foo(s: String) = s } 我想扩展伴生对象的foo方法,使其具有属性函数,为此,我使用以下隐式类: implicit class ExtendApi(api: Api.type) { object foo { def asInt(s: String): Int = s.t
trait Api {
def foo(s: String): String
}
object Api extends Api {
override def foo(s: String) = s
}
我想扩展伴生对象的foo方法,使其具有属性函数,为此,我使用以下隐式类:
implicit class ExtendApi(api: Api.type) {
object foo {
def asInt(s: String): Int = s.toInt
}
}
println (Api.foo.asInt("1")) // Does not work
然而,使用它确实可以编译。我得到一个错误:
missing argument list for method foo in object Api
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `foo _` or `foo(_)` instead of `foo`.
scala似乎没有解析隐式定义来查找foo
对象
我试图通过写作来表达:
println (implicitly[Api.type].foo.asInt("1"))
现在我得到另一个错误:
could not find implicit value for parameter e: Playground.this.Api.type
这个新错误对我来说毫无意义
我想做的事可能吗?如何修复错误?多谢各位
Scala编译器永远不会选择比普通方法更合适的扩展方法。此外,我不确定是否可以使用内部对象作为扩展方法。你为什么需要这个?它更喜欢有不同签名的分机;带有apply的内部对象可以进行扩展(因为它只是在寻找一个成员),但是使用相同的名称,spec 7.3说只有方法才符合条件。你激发了一个bug报告:@som snytt Oh dam,这是一个有趣的bug报告