Error in Type - Variance - Scala -


def test[t<:anyval](s:t):t={ s+1 } 

this showing error:

:11: error: type mismatch;

found : int(1)

required: string s+1

when t type of anyval why required string?

i'm not sure why you're getting error string - although suspect it's because of other code haven't included in answer - code posted can not work because anyval constraint not suffice if want call + method on s parameter.

this speculation, because haven't mentioned you're trying do, imagine along lines of "i want function adds 1 number, regardless of type".

if so, anyval restrictive (e.g. bigint not anyval). in fact, don't need such constraint @ all, rather need access numeric[t] instance. numeric type class providing several operators - including +.

usage (you might have scala's implicits if haven't understand this):

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

you can still add anyval constraint if you're sure need it.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -