I have been trying to determine how one might write a type parameter that restricts a function to types that support relational operators?
For example:
def biggerOf[A <: ???](a: A, b: A): A = { if (a > b) a else b }
Where ??? is my dilemma. Advanced type parameter bits are new to me, so asking for a little help. Thought AnyVal might be a winner but for Unit type (and Boolean which won't break, but won't work either). Thanks for any ideas.
You want to bring the Ordering typeclass into play.
import scala.math.Ordering.Implicits.infixOrderingOps
def biggerOf[A:Ordering](a: A, b: A): A = { if (a > b) a else b }
A:Ordering restricts A to types in the Ordering typeclass and infixOrderingOps enables the convenience operators (methods) such as <, >=, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With