在 Scala 中绑定类型之后的另一个子类型

Pha*_*tom 4 scala context-bound chisel

class PEControl[T <: Data : Arithmetic](accType: T),这是来自 riscv-gemmini 的类定义。的Data类型是在凿的基本数据类型,Arithmetic提供了关于某些算术运算Data,和abstract class Arithmetic[T <: Data]

用于的语法是<: Type : Type什么,这是什么意思?我发现语法是TypeParamBounds ::= TypeBounds {‘:’ Type}这里调用的。哪里可以详细了解一下,谢谢。

Sim*_*mY4 5

类型边界是以下内容的简写:

class PEControl[T <: Data : Arithmetic](accType: T)

// equivalent to

class PEControl[T <: Data](accType: T)(implicit noName: Arithmetic[T])

// which means in both cases in the body of your class 
// you can summon instances of arithmetic for all Ts

class PEControl[T <: Data : Arithmetic](accType: T) {

  def doSomethingWithT(t1: T, t2: T): Unit = {
    implicitly[Arithmetic[T]].plus(t1, t2)
  }

}
Run Code Online (Sandbox Code Playgroud)


Mar*_*lic 5

<:类型:类型,这是什么意思?

Scala 结合了面向对象的概念和函数式编程的概念。例如,在 Scala 中,可以使用子类型约束和类型类约束来约束类型参数

T <: Data                // subtyping contraint on T
T : Arithmetic           // type class constraint on T
T <: Data : Arithmetic   // subtyping and type class contraint on T
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,这些编译时约束的重点是告诉编译器类型参数T提供哪些功能,即我们可以对 type 的值调用哪些方法T。决定对类型参数施加什么样的约束是一个设计决策。一些程序员喜欢带有类型类的参数多态的纯函数式编程方法,其他人更喜欢更面向对象的子类型方法,还有一些人认为我们还没有探索 Scala 提供的混合方法的真正威力。无论哪种方式,Scala 都不会为您做出决定。附带说明一下,在某些语言(例如 Rust)中不鼓励或完全删除子类型多态性。