why scala can't infer the type of method parameters
I am wondering why scala can't infer the type of method parameters.I can see that in haskel (which also has type inference) can do the same.开发者_运维知识库 Then why not for scala ?
First of all the situation in Scala is quite a bit different than in Haskell because it's an OO language and type-inference in an object oriented setting is a bit more complicated.
The only OO language that I know which comes close to full type inference is OCaml. OCaml does so by making extensive use of structural typing (the inferred type of o
in let f o = o.foo 42
is "Object which has a foo
method which takes an int
as an argument" and the inferred return type is "whatever the return type of o.foo
is", which is the only useful type to infer here).
However Scala has many additional features (overloading, implicit conversions) that get in the way of OCaml's approach and make full, global type inference impossible.
To put it simply, Hindley-Milner, the type inference algorithm used by Haskell, doesn't work in the presence of subtyping.
精彩评论