access to a type's companion object

不羁的心 提交于 2019-12-06 09:40:01

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!