首页 > 解决方案 > 在 scala 中绑定的类型之后的另一个子类型

问题描述

class PEControl[T <: Data : Arithmetic](accType: T),这是来自 riscv-gemmini 的类定义。Datatype 是 chisel 中的基本数据类型,提供对, 和Arithmetic的一些算术运算。Dataabstract class Arithmetic[T <: Data]

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

标签: scalachiselcontext-bound

解决方案


类型边界是以下的简写:

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)
  }

}

推荐阅读