Conditional methods of Scala generic classes with restrictions for type parameters

前端 未结 3 569
花落未央
花落未央 2021-01-05 01:10

I believe that a generic class may make one of its methods available only assuming that its type parameters conform to some additional restrictions, something like (syntax i

3条回答
  •  星月不相逢
    2021-01-05 01:45

    You can also use a type bound on the type parameter, which is enforced by an implicit argument:

    trait Col[T] extends Traversable[T] {
        def sum(implicit ev: T <:< Int) :T = (0/:this)(_+_)
    }
    

    <:< is actually a class, expressed in infix notation, defined in Predef.scala and explained in many places, including here

    <:< means 'must be a subtype of'

    You can also use =:= 'must be equal to' and X <%< Y 'must be viewable as' (ie. there is an implicit conversion to X from Y)

    For a more detailed explanation of type constraints, see this SO question.

提交回复
热议问题