0
def test[T<:AnyVal](s:T):T={
s+1
}

This is showing this error:

:11: error: type mismatch;

found : Int(1)

required: String s+1

When T is type of AnyVal why it required String?

  • 2
    This is a very commonly asked question, phrased slightly differently: http://stackoverflow.com/questions/3127934/parametric-type-function-requires-a-string-as-second-parameter – Michael Zajac Feb 06 '16 at 15:49

1 Answers1

0

I'm not sure why you're getting an error about String - although I suspect it's because of other code that you haven't included in this answer - but the code you posted can not work because an AnyVal constraint does not suffice if you want to call the + method on your s parameter.

This is speculation, because you haven't mentioned what exactly you're trying to do, but I imagine it is along the lines of "I want a function that adds 1 to any number, regardless of its type".

If so, AnyVal is likely to restrictive (e.g. BigInt is not an AnyVal). In fact, you don't need such a constraint at all, rather what you need is access to a Numeric[T] instance. Numeric is a type class providing several operators - including +.

Usage would look like this (you might have to look into scala's implicits if you haven't already to understand this):

def test[T](x: T)(implicit numeric: Numeric[T]): T = {
    numeric.plus(x,numeric.one)
}

You can still add the AnyVal constraint to this if you're sure that you really need it.

Cubic
  • 14,902
  • 5
  • 47
  • 92
  • 2
    The error is tied to the code posted by the OP. Not all types that extend `AnyVal` have a `+` method (`Boolean` for example), so when the compiler sees `+` on a general `AnyVal`, it tries to implicitly convert `s` to a `String` via `toString`, which every type has. However, it won't also convert `1` to a `String` (as that would be two steps of implicit conversion), so it stops there with a type mismatch. – Michael Zajac Feb 06 '16 at 15:47
  • @m-z Ah, that makes sense, thanks for that explanation – Cubic Feb 06 '16 at 17:52