scala generic function return type -
i tried writing function generic return type doesn't work unless cast return type. please see function getsomething()
below expected work without casting. might doing wrong here?
trait sup class sub extends sup { def getstring = "i sub" } class sub2 extends sup { def getint = 100 } def getsomething[a <: sup](str: string) : = { str match { case "sub" => getsub.asinstanceof[a] case "sub2" => getsub2.asinstanceof[a] } } def getsub(): sub = { new sub } def getsub2() : sub2 = { new sub2 } val x = getsomething[sub]("sub").getstring val y = getsomething[sub2]("sub2").getint
as alexey mentions, instanceof
needed force link between expected type , type of object returned. it's equivalent of saying: "compiler, trust me, i'm giving 'a'" , it's not safe depends of provide correct type.
if want type system figure things out us, need give additional information. 1 way in scala define factory knows how produce instances of our types , evidence allows factory return our specific types.
this version of code above introducing such construct , using contextbounds
obtain right factory instance of type want.
trait sup class sub extends sup { val str = "i'm sub" } class sub2 extends sup { val number = 42 } trait supprovider[t <: sup] { def instance:t } object supprovider { def getsomesup[t<:sup:supprovider]: t = implicitly[supprovider[t]].instance implicit object subprovider extends supprovider[sub] { def instance = new sub } implicit object sub2provider extends supprovider[sub2] { def instance = new sub2 } } supprovider.getsomesup[sub].str // res: string = i'm sub supprovider.getsomesup[sub2].number // res: int = 42
Comments
Post a Comment