Scala 具有抽象类型成员的具体类
鉴于以下特点和阶级。为什么要编译?这真的可以用来做什么吗Scala 具有抽象类型成员的具体类,scala,types,Scala,Types,鉴于以下特点和阶级。为什么要编译?这真的可以用来做什么吗 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
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>
它实际上是一个功能,但我找不到它的动机:。它看起来对我来说毫无用处。x想要的类型不存在,因此无法将其传递给方法。我想,无害的无用性是否应该是编译时错误是一个品味问题 如果你看看x的实际功能,它会反编译:
public java.lang.Object x(java.lang.Object);
Code:
0: aload_1
1: areturn
这正是identity方法应该做的(不管类型如何加载参数,都返回它)。您可以用更少的代码编写等效的代码:
trait AbstractType { type T }
class Useless extends AbstractType { def identity(t: AbstractType#T) = t }
除了没有类型AbstractType#T之外,我们还有无用性
除非我遗漏了什么。在您的示例中,编译器添加了默认的类型界限
>:Nothing trait T{type A>:Nothing 1:T#A>
:6:错误:类型不匹配;
发现:Int(1)
必填项:T#A
1:T#A
^
scala>特征T{typea>:Int 1:T#A
res6:T#A=1
scala>“”:T#A
:6:错误:类型不匹配;
找到:java.lang.String(“”)
必填项:T#A
“”:T#A
^
为什么?B在Mixed中的另一个容器的实例中是A,因此x的签名在另一个容器x和Impl.x之间是一致的。或者我遗漏了什么吗?@Randall,类型A
是抽象的,我看不到它在任何地方变得具体。因此我希望Impl
不编译,返回一个“需要抽象的”错误。这是有意允许的;有关详细信息,请参阅。trait T{type A>:Int
trait AbstractType { type T }
class Useless extends AbstractType { def identity(t: AbstractType#T) = t }
scala> trait T { type A >: Nothing <: Any }
defined trait T
scala> 1: T#A
<console>:6: error: type mismatch;
found : Int(1)
required: T#A
1: T#A
^
scala> trait T { type A >: Int <: Int }
defined trait T
scala> 1: T#A
res6: T#A = 1
scala> "": T#A
<console>:6: error: type mismatch;
found : java.lang.String("")
required: T#A
"": T#A
^