Using Implicit Type Constraint

As far as I know, there are two ways to add a type constraint.

trait Dummy

First way

def doStuff[T <: Dummy](x: T) = x

Second way

def doStuff[T](x: T)(implicit x: T <:< Dummy) = x

Both achieve the same result.

I'm just wondering which scenarios I should use directly at the upper bound or lower bound, or should I use implicit to add a type restriction.

+4
source share
1 answer

The creation of an implicit object is required each time the call is invoked, the other simply places a type constraint on the object passed to the function. In general, I would prefer an ad in which you indicate [T <: Dummy], rather than implicit.

, , , . , List[A] :

 def sum(implicit ev: Numeric[A]) = ...

" " A " , " sum ", ..." , , :

 class Foo[T](value: T){
   def doubleString = value.toString() + value.toString()

   def specialSauce(implicit ev: T <:< Dummy): Dummy = ...
 }

Foo[Int], , specialSauce , T Dummy.

+5

Source: https://habr.com/ru/post/1537704/


All Articles