我想为doubles数组定义一些隐式方法,以使我的代码更简洁。理想情况下,它们应该如下所示:
type Vec = Array[Double]
implicit def enrichVec(v: Vec) = new {
def /(x: Double) = v map (_/x)
def *(u: Vec) = (v zip u) map {case (x,y) => x*y} sum
def normalize = v / math.sqrt(v * v)
}然而,normalize函数并不像编写的那样工作,因为Scala不会递归地应用隐式方法。具体地说,我得到了一个错误Note: implicit method enrichVec is not applicable here because it comes after the application point and it lacks an explicit result type。我可以通过显式地写出normalize的代码来避免这一点,但这将是丑陋的。有没有更好的解决方案?
发布于 2011-12-01 00:12:38
这是可行的:
type Vec = Array[Double]
abstract class RichVec(v: Vec) {
def /(x: Double): Vec
def *(u: Vec): Double
def normalize: Vec
}
implicit def enrichVec(v: Vec): RichVec = new RichVec( v ) {
def /(x: Double) = v map (_/x)
def *(u: Vec) = (v zip u) map {case (x,y) => x*y} sum
def normalize = v / math.sqrt(v * v)
}但还有其他方法可以做到这一点。最重要的是指定隐式的返回类型。
https://stackoverflow.com/questions/8320826
复制相似问题