Kevin Atteson
Kevin Atteson

Reputation: 51

Type constraints on the companion object of a type parameter in scala

I would like to define a parameterized class called ExtendedNumber which would take some form of whole number such as Int or Byte and extend it so as to include infinity, -infinity and null. In particular, I'd like to use MaxValue to represent infinity. If MaxValue was a static member, I believe I could do something like this:

class ExtendedNumber[T <: {val MaxValue : T}] {
  val infinity = T.MaxValue
  ...
}

However, since MaxValue is defined in the companion object, I believe I need to put a type constraint on the companion object. Is this possible? I'm also open to other solutions of the general problem.

Upvotes: 2

Views: 1149

Answers (1)

Jesper Nordenberg
Jesper Nordenberg

Reputation: 2104

The general solution is to add a type class, for example:

trait ExtendedNumber[T] {
  def infinity: T
}

implicit object extendedInt extends ExtendedNumber[Int] {
  def infinity = Int.MaxValue
}

def foo[T](v: T)(implicit en: ExtendedNumber[T]) = v == en.infinity

Upvotes: 3

Related Questions