考虑以下典型的Scala'pimp'代码:
class PimpedA(a:A){
def pimp() = "hi"
}
implicit def pimpA(a:A) = new PimpedA(a)
new A(){
pimp() //<--- does not compile
}
Run Code Online (Sandbox Code Playgroud)
但是,将其更改为:
new A(){
this.pimp()
}
Run Code Online (Sandbox Code Playgroud)
使它工作.它应该与Scala编译器不一样吗?
编辑:有没有任何解决方案可以让它工作而不必添加this.
?
我很确定在Scala中这很简单,但我似乎无法弄清楚类型系统需要做什么提示才能使其工作.
我想要一个抽象的Printable类,然后隐式地将其他类转换为它.更具体地说,我想隐式地将Byte转换为Printable,将Array [Byte]转换为Printable.
所以我做到了这一点:
abstract class Printable{
def print():String
}
class PrintableByte(b:Byte) extends Printable{
def print() = "" /*return something*/
}
implicit def printableByte(b:Byte) = new PrintableByte(b)
class PrintableArray(a:Array[Printable]) extends Printable{
def print() = {
for(i <- 0 until a.length) a(i).print() // no problems here
"" /*return something*/
}
}
implicit def printableArray(a:Array[Printable]) = new PrintableArray(a)
Run Code Online (Sandbox Code Playgroud)
然而:
val b:Byte = 0
b.print() //no problem here
val a= new Array[Byte](1024)
a.print() //error: value print() is not a member of Array[Byte]
Run Code Online (Sandbox Code Playgroud)
我期望类型系统能够理解Array …