Conditional methods of Scala generic classes with restrictions for type parameters

前端 未结 3 566
花落未央
花落未央 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:56

    In this case you can only use an implicit parameter, as the type gets determined before the method call.

    trait Col[T] extends Traversable[T] {
      def sum(implicit num: Numeric[T]) :T = ???
    }
    

    If the method you are calling would be parameterized, you could use context bounds, which are just syntactic sugar for the implicit parameter bound to the type parameter:

    def foo[A](implicit ev: Something[A]) = ???
    

    is equivalent to

    def foo[A : Something] = ???
    

提交回复
热议问题