I have a class with a constrained type parameter.
I've tried with identity but the return type is not precise.
And in the method identityTP, I need to specify again the constraint
How to avoid to duplicate this constraint with methods that work on this type ?
Here is an example :
sealed trait Location
case object Single extends Location
case object Multi extends Location
final case class Log[L <: Location](l: L)
def identity(log: Log[_]): Log[_] = log
def identityTP[L<: Location](log: Log[L]): Log[L] = log
Actually this is not a duplication.
Linand
Linare two completely different type parameters. This could be more clear if you used different identifiers
An upper bound for one type parameter doesn't duplicate an upper bound for other type parameter.
Also this is not a duplication because actually upper bounds can be different
If you don't want to create the second type parameter you can make
identityTPnested intoLog(making itLog's method)Sometimes it can help if you make
La type member rather than type parameterNotice that although we have to repeat upper bound in
applybut we don't have inidentityTP.Normally it's not a big deal to repeat upper bound when necessary
When this becomes cumbersome
you should redesign your abstractions. For example
or
Also sometimes you can play with replacing type bounds with type constraints
Although this doesn't remove repetitions but there are ways to fight against repetitions among implicit parameters as well (type classes). See How to wrap a method having implicits with another method in Scala?