Is it possible to get the MinValue
- or MaxValue
of an unknown Type T? As in Int
which has Int.MinValue
and Int.MaxValue
??
Thanks
As @mpilquist said in the comments above, you can create a Bounded
type class a la Haskell.
Code example:
trait Bounded[A] {
def minValue: A
def maxValue: A
}
object Bounded {
def apply[A](min: A, max: A) = new Bounded[A] {
def minValue = min
def maxValue = max
}
implicit val intBounded = Bounded(Int.MinValue, Int.MaxValue)
implicit val longBounded = Bounded(Long.MinValue, Long.MaxValue)
}
object Main {
def printMinValue[A : Bounded](): Unit = {
println(implicitly[Bounded[A]].minValue)
}
def main(args: Array[String]): Unit = {
printMinValue[Int]() // prints -2147483648
printMinValue[Long]() // prints -9223372036854775808
}
}
Addendum:
You can even extend it to your custom types, as shown below:
// A WeekDay ADT
sealed abstract trait WeekDay
case object Mon extends WeekDay
case object Tue extends WeekDay
case object Wed extends WeekDay
case object Thu extends WeekDay
case object Fri extends WeekDay
case object Sat extends WeekDay
case object Sun extends WeekDay
object WeekDay {
implicit val weekDayBounded = Bounded[WeekDay](Mon, Sun)
}
printMinValue[WeekDay]() // prints Mon
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