Scala method unable to infer return type -


i failed understand why, if specify return type of function scala compiler complains. pretty sure happening because using f-bounded polymorphism. in on scala(2.11) shell. here class definition:

trait base[t <: base[t]]  case class derived(id: long) extends base[derived] 

this works (without explicit return type):

def buildthisworks1[t<:base[t]]() = derived(1) 

however not work:

def buildnotworking[t<:base[t]]() : t = derived(1) <console>:10: error: type mismatch;  found   : derived  required: t        def buildnotworking[t<:base[t]]() : t = derived(1) 

if typecast derived class of type t works, confusing me.

def buildthisworks2[t<:base[t]]() : t =  derived(1).asinstanceof[t] 

note in second definition make derived instance of t (which according me redundant since derived subtype of base works).

def buildthisworks2[t<:base[t]]() : t =  derived(1).asinstanceof[t] 

when don't specify return type of method, compiler infers it:

scala> def buildthisworks1[t <: base[t]]() = derived(1) buildthisworks1: [t <: base[t]]()derived 

here, return type inferred derived, , not t. in fact, type parameter absolutely nothing here, because method return derived type.


the following cannot work, because not know t = derived. t can type satisfies constraint t <: derived[t]. while it's true there 1 type here satisfies condition, compiler isn't going assume t = derived. add class extends base[extra], , mysteriously cause method break (if worked in first place).

def buildnotworking[t <: base[t]]() : t = derived(1) 

the type-cast works because forcing type of derived(1) of t. if t derived, okay.

def buildthisworks2[t <: base[t]]() : t =  derived(1).asinstanceof[t] 

but cast telling compiler ignore type errors, cause problems @ runtime. if t not derived, you're going have problem.

class bad extends base[bad]  scala> buildthisworks2[bad] java.lang.classcastexception: derived cannot cast bad   ... 33 elided 

we classcastexception, because t bad type, , derived cannot cast it.


all in all, it's unclear want do. typically, type parameters inferred parameters of method. here, there no parameters method, there nothing infer parameter type. compiler okay this, because can still manually supply type parameter (as did in example caused exception). type parameter t cannot inferred return value of method, because should depend on caller via parameters (or static).

essentially, type parameter these methods don't serve purpose, , ignored since you're returning same type derived every time. make more sense accept base[t] parameter, it, , return (maybe?).

def dosomething[t <: base[t]](t: t): t = t // not creative 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -