Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Min/MaxValue of unkwown Type

Tags:

generics

scala

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

like image 478
xyz Avatar asked Dec 28 '22 17:12

xyz


1 Answers

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
like image 126
missingfaktor Avatar answered Jan 14 '23 05:01

missingfaktor