访问类型的伴随对象 [英] 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
}
但这相当冗长,minVal
以 :Long
的形式出现,这使得与 i: I
的比较变得复杂.
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.
推荐答案
您可以使用类型类来获取最小值:
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 }
}
我们可以使用这个类型类来获取传递给foo
函数的值的类型的最小值:
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
这篇关于访问类型的伴随对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!