Take the 2-minute tour ×

I have the following method:

def toNumber[T <: AnyVal](value:String, default:T)(implicit n: Numeric[T]):T = {
    val str = value.trim
    var s = n.zero
    if (value.trim.isEmpty) {
    } else {
      if (default.isInstanceOf[Long])
        s = n.plus(n.zero,str.toLong.asInstanceOf[T])
      else if (default.isInstanceOf[Int])
        s = n.plus(n.zero,str.toInt.asInstanceOf[T])

Is it possible to streamline this somehow so it looks at the type of T (e.g. Int, Long, etc.) and uses it to call the right "to" method (e.g. toInt, toLong, etc.)?

As a bonus question, can I somehow limit T to just Int and Long rather than any subclass of AnyVal?

Thanks, John

share|improve this question

1 Answer 1

up vote 10 down vote accepted

If you want to limit T to specific numeric instances, it might be a good idea to provide your own typeclass (thus providing an answer to your initial question):

trait Natural[T] { def from(s : String) : T }
implicit object IntNatural = new Natural[Int] { 
  def from(s : String) = s.toInt 
implicit object LongNatural = new Natural[Long] { 
  def from(s : String) = s.toLong 

Then your method:

def toNumber[T : Natural](value : String, default : T) : T = 
  if (value.trim.isEmpty)

However, I would personally re-write this method signature as:

def natural[T : Natural](value : String) : Option[T]

And then users would use getOrElse default at the use-site. For example:

natural[Int]("42") getOrElse 23
share|improve this answer
This is probably the best solution, although I might use a different name for the type class as Integral is already a Scala type class. –  derekjw Apr 25 '11 at 16:35
Also, I would have a trait IntegralImplicits that contains just the implicit IntIntegral, and then have an object Integral that extends IntegralImplicits and also contains the implicit LongIntegral. Then when a user calls 'toNumber("42")' it is by default an Option[Long]. If the user calls 'toNumber[Int]("42")' it is an Option[Int]. –  derekjw Apr 25 '11 at 16:41
Agree about Integral - have changed to Natural (a bit of a maths lie, though) –  oxbow_lakes Apr 25 '11 at 17:13

Your Answer


