问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/33112637/access-to-a-types-companion-object