Scala - 如何定义引用自身的结构类型?
我正在尝试编写一个通用的 interpolate
方法,该方法适用于具有两个方法(*
和 +
)的任何类型,如下所示:
trait Container {
type V = {
def *(t: Double): V
def +(v: V): V
}
def interpolate(t: Double, a: V, b: V): V = a * (1.0 - t) + b * t
}
但这不起作用(在 Scala 2.8.0.RC7 上),我收到以下错误消息:
<console>:8: error: recursive method + needs result type
def +(v: V): V
^
<console>:7: error: recursive method * needs result type
def *(t: Double): V
^
如何正确指定结构类型? (或者有更好的方法来做到这一点吗?)
I'm trying to write a generic interpolate
method that works on any type that has two methods, a *
and a +
, like this:
trait Container {
type V = {
def *(t: Double): V
def +(v: V): V
}
def interpolate(t: Double, a: V, b: V): V = a * (1.0 - t) + b * t
}
This doesn't work though (on Scala 2.8.0.RC7), I get the following error messages:
<console>:8: error: recursive method + needs result type
def +(v: V): V
^
<console>:7: error: recursive method * needs result type
def *(t: Double): V
^
How do I specify the structural type correctly? (Or is there a better way to do this?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,您可以使用类型类方法(例如Scalaz):
那么显然您需要在您关心的所有类型的范围内进行(隐式)类型类转换:
然后可以轻松运行:
Surely you could solve this problem using the typeclasses approach (of e.g. Scalaz):
Then obviously you would need a (implicit) typeclass conversion in scope for all the types you cared about:
Then this can be run easily:
AFAIK,这是不可能的。这是我自己的第一个问题。
AFAIK, this is not possible. This was one of my own first questions.