0

I know this question may be answered a lot of times, however I cannot find a post that can solve my question. My question is I want to write a generic function that can take Int, Double or BigDecimal and do the calculation.

def foo[T: Numeric](returns: Seq[T])(implicit ev: T => Ordered[T]): Seq[T]= {
    returns.filter(_ >= 0)
}

However I got a Type Match error, because 0 is a Int. If there any way that can make it work for any Numeric type.

2 Answers 2

1

Try this.

def foo[T](returns: Seq[T])(implicit N: Numeric[T]): Seq[T] = {
  import N._
  returns.filter(_ >= N.zero)
}

The scaladoc is your friend.

Sign up to request clarification or add additional context in comments.

Comments

1

Would rather ...

def foo[T](returns: Seq[T])(implicit n: Numeric[T]): Seq[T] =
  returns.filter { v => n.compare(v, n.zero) >= 0 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.