具有抽象类型成员的具体类 [英] Concrete classes with abstract type members
问题描述
鉴于以下特征和类别.为什么要编译?这实际上可以用于某些事情吗?
Given the following traits and class. Why does this compile? Can this be actually used for something?
trait Container {
type A
}
trait AnotherContainer[B]{
def x(b : B) : B
}
trait Mixed extends Container with AnotherContainer[Container#A]
class Impl extends Mixed{
def x(a : Container#A) = a
}
new Impl().x _
scala> new Impl().x _
res0: (Container#A) => Container#A = <function>
更新:
class Baz { type T; }
实际上是一个功能,但我找不到它的动机:#1753.
Is actually a feature but I could not find the motivation for it: #1753.
推荐答案
如果对我没用,它看起来也无害.x 想要的类型不存在,因此您无法将其传递给方法.我想,无害的无用是否应该是编译时错误是一个品味问题.
It looks harmless if useless to me. The type that x wants doesn't exist, so you can't pass it to the method. Whether harmless uselessness should be a compile-time error is a matter of taste, I suppose.
如果你看看 x 实际上做了什么,它就是这样反编译的:
If you look at what x actually does, it decompiles thusly:
public java.lang.Object x(java.lang.Object);
Code:
0: aload_1
1: areturn
这正是 identity 方法应该做的事情(加载参数而不考虑类型,返回它).你可以用更少的代码写出等价的东西:
which is exactly what the identity method should do (load the argument regardless of type, return it). You can write something equivalent with much less code:
trait AbstractType { type T }
class Useless extends AbstractType { def identity(t: AbstractType#T) = t }
除了AbstractType#T 没有任何类型,所以我们又无用了.
Except nothing has type AbstractType#T, so again we have uselessness.
除非我遗漏了什么.
这篇关于具有抽象类型成员的具体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!