【发布时间】:2014-02-28 21:11:04
【问题描述】:
使用 scala 2.10.3,我的目标是完成以下工作:
object A {
implicit class Imp(i: Int) {
def myPrint() {
println(i)
}
}
}
object B {
implicit class Imp(i: String) {
def myPrint() {
println(i)
}
}
}
import A._
import B._
object MyApp extends App {
3.myPrint()
}
这失败了
value myPrint is not a member of Int
如果我给 A.Imp 和 B.Imp 赋予不同的名称(例如 A.Imp1 和 B.Imp2),它会起作用。
再深入一点,隐式转换似乎也存在同样的问题。
这行得通:
object A {
implicit def Imp(i: Int) = new {
def myPrint() {
println(i)
}
}
implicit def Imp(i: String) = new {
def myPrint() {
println(i)
}
}
}
import A._
object MyApp extends App {
3.myPrint()
}
而这不是:
object A {
implicit def Imp(i: Int) = new {
def myPrint() {
println(i)
}
}
}
object B {
implicit def Imp(i: String) = new {
def myPrint() {
println(i)
}
}
}
import A._
import B._
object MyApp extends App {
3.myPrint()
}
为什么?这是scala编译器中的错误吗?我需要这种情况,因为我的对象 A 和 B 派生自相同的特征(带有类型参数),然后定义了其类型参数的隐式转换。在这个特性中,我只能给隐式转换一个名字。我希望能够将更多这些对象导入我的范围。有没有办法做到这一点?
编辑:我不能给隐式类起不同的名字,因为上面的例子只是解决问题。我的实际代码看起来更像
trait P[T] {
implicit class Imp(i: T) {
def myPrint() {
...
}
}
}
object A extends P[Int]
object B extends P[String]
import A._
import B._
【问题讨论】:
-
听起来您所需要的只是成员函数的名称相同,而不是隐式名称本身。为什么你需要同时调用“Imp”?
-
我只有一个地方可以定义隐式。这是在通用父特征中。所以我只能给它一个名字。然后所有对象都从该特征继承并允许将其用于不同的类型。
标签: scala implicit-conversion scala-2.10