Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another subtype after a type bound in scala

class PEControl[T <: Data : Arithmetic](accType: T), this is a class definition from riscv-gemmini. The Data type is the basic data type in chisel, Arithmetic provides some arithmetic operation on Data, and abstract class Arithmetic[T <: Data].

What is the syntax used for the <: Type : Type, what does this mean? I find that the syntax is called TypeParamBounds ::= TypeBounds {‘:’ Type} from here. Where can I get some detail about it, thanks.

like image 884
Phantom Avatar asked Dec 23 '22 15:12

Phantom


2 Answers

<: Type : Type, what does this mean?

Scala combines both object-oriented concepts with functional programming concepts. For example, in Scala type parameters can be constrained using both subtyping constraints as well as type class constraints

T <: Data                // subtyping contraint on T
T : Arithmetic           // type class constraint on T
T <: Data : Arithmetic   // subtyping and type class contraint on T

In both cases the point of these compile-time constraints is to tell compiler what capabilities type parameter T provides, that is, what methods we can call on values of type T. Deciding what kinds of constraints to put on your type parameters is a design decision. Some programers like pure functional programming approach of parametric polymorphism with type classes, others prefer more object-oriented subtyping approach, and some argue that we still have not explored the true power of the mixed approach Scala provides. Either way Scala does not make the decision for you. As a side note, subtyping polymorphism is discouraged or completely removed in some languages such as Rust.

like image 160
Mario Galic Avatar answered Jan 05 '23 18:01

Mario Galic


Type bounds are a shorthand for:

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

}
like image 36
SimY4 Avatar answered Jan 05 '23 18:01

SimY4