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?
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?
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.