jwvh
jwvh

Reputation: 51271

access to a type's companion object

I have a variable of some type and I'd like to get information from the companion object. For example, I thought I might be able to do something like this:

def foo[I: Integral](i:I): = {
  val minVal = i match {
    case _:Byte  => Byte.MinValue
    case _:Char  => Char.MinValue
    case _:Int   => Int.MinValue
    case _:Long  => Long.MinValue
    case _:Short => Short.MinValue
  }
  // compare i and minVal
}

But this is rather verbose and minVal comes out as :Long which complicates comparisons with i: I.

I was hoping I could find something concise and direct but I suspect this requires reflection, which is often neither.

Upvotes: 2

Views: 96

Answers (1)

Peter Neyens
Peter Neyens

Reputation: 9820

You could use a type class to get the minumum value :

trait MinValue[T] { def minValue: T }
object MinValue {
  implicit val minByte = new MinValue[Byte] { def minValue = Byte.MinValue }
  implicit val minChar = new MinValue[Char] { def minValue = Char.MinValue }
  implicit val minLong = new MinValue[Long] { def minValue = Long.MinValue }
  implicit val minInt  = new MinValue[Int]  { def minValue = Int.MinValue }
}

We can use this type class to get the minumum value for the type of the value passed to the foo function :

def foo[I: Integral](i: I)(implicit min: MinValue[I]) = 
  implicitly[Integral[I]].compare(i, min.minValue)
// or 
def foo2[I: Integral: MinValue](i: I) = {
  val minVal = implicitly[MinValue[I]].minValue
  implicitly[Integral[I]].compare(i, minVal)
}

foo(5) // Int = 1
foo(Int.MinValue) // Int = 0

foo2(-127.toByte) // Int = 1
foo2(-128.toByte) // Int = 0

Upvotes: 4

Related Questions