Hawk66 Hawk66 - 3 months ago 6
Scala Question

Equivalent of C# type constraint (where) in Scala

In C# you can define a method

public T GetComponent<T>() where T : IComponent


to express that T has to be of IComponent.

How can I express the same in Scala?

Answer

In Scala, this is called an Upper Type Bound (as you can also have a Lower Type Bound, a constraint that doesn't exist in C#). You define them like this:

def getComponent[T <: IComponent]