Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type parameter to ensure relational operators

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.

like image 302
reverend Avatar asked Nov 25 '25 05:11

reverend


1 Answers

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.

like image 54
jwvh Avatar answered Nov 28 '25 14:11

jwvh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!