我希望编写一个函数,该函数可以处理任何可以添加到其自身类型的其他成员的值(无论"添加"在上下文中是什么意思).这种类型的明显(嘿嘿)定义:
type Addable = { def +(a : Addable) : Addable }
Run Code Online (Sandbox Code Playgroud)
这给了我一个我根本不懂的错误:递归方法+需要结果类型
为什么不是最后: Addable的结果类型?为什么它认为+是递归的呢?
但我发现了一个更普遍的问题,试图在自己的定义中引用一个类型:
type T = { def f: T }
Run Code Online (Sandbox Code Playgroud)
但后来我有了一个脑波:用Java的方式解决它!
type T[T] = { def f: T }
Run Code Online (Sandbox Code Playgroud)
这个汇编了!
但现在我还有两个问题.
首先,我不知道如何使用T型.特别是,
def n(a:T) = a.f
Run Code Online (Sandbox Code Playgroud)
给出完全明智但令人沮丧的"类型T取类型参数"错误.
其次,尝试将此模式应用于原始问题
type Addable[Addable] = { def +(a : Addable) : Addable }
Run Code Online (Sandbox Code Playgroud)
导致一个完全不可理解的"结构细化中的参数类型可能不会引用在该细化之外定义的抽象类型".(实际的问题并不在于它是"+" - 感谢上帝和马丁,因为那会让我的脑袋变得一团糟 - 只需要一个Addable作为参数.)
所以
我有一种宗教般的信念,认为这个问题是可以解决的.
psp*_*psp 13
那些是不同的Ts.
scala> type T[T] = { def f: T }
defined type alias T
scala> var x: T[Int] = null
x: T[Int] = null
scala> x = new AnyRef { def f = 5 }
x: T[Int] = $anon$1@44daa9f1
Run Code Online (Sandbox Code Playgroud)
当你写:
type Addable[Addable] = { def +(a : Addable) : Addable }
Run Code Online (Sandbox Code Playgroud)
您有一个Addable类型,它接受一个类型参数,也称为Addable.这是一个人们经常混淆的类似变化.
scala> def f[Int](x: Int) = x * x
<console>:7: error: value * is not a member of type parameter Int
def f[Int](x: Int) = x * x
^
Run Code Online (Sandbox Code Playgroud)
你的问题的实际答案是"你不能",但我不想破坏你的宗教信仰,所以我会说"结构类型以神秘的方式运作".如果你想继续执行宗教任务,你可以访问这里,这就解释了为什么你不能.
http://article.gmane.org/gmane.comp.lang.scala/7013
| 归档时间: |
|
| 查看次数: |
882 次 |
| 最近记录: |