scala - 具有抽象类型成员的具体类

标签 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 _

scala> new Impl().x _
res0: (Container#A) => Container#A = <function>

更新:
class Baz { type T; }

实际上是一个功能,但我找不到它的动机:#1753 .

最佳答案

在您的示例中,编译器添加了 >: Nothing <: Any 的默认类型边界。 .下面的第二个示例显示了抽象类型变得可用(如果没有用)的情况。

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
       ^

关于scala - 具有抽象类型成员的具体类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2115678/

相关文章:

TypeScript 无法在函数类型中派生类型约束

list - Scala:为什么 foldLeft 不能用于两个列表的连接?

scala - 如何让 Intellij 对失败的测试提供文本差异比较

json - 如何在scala中解析HTTP请求返回的Json数据

c# - 为什么具体化的泛型很难与更高级的类型结合使用?

c# - 从字节转换 unicode 字符

java - 如何向Dataframe添加一些信息?

java - 如何在不知道 avro 模式的情况下在 scala 中读取 Avro 编码的 kafka 消息?

C# 字节数组到固定 int 指针

f# - 使用 F# 的可选参数和选项类型