Hacker News new | ask | show | jobs
by ygra 3746 days ago
How would type inference for local variables mess with fields?
1 comments

according to Spring's documentation[1]:

@Autowired is fundamentally about type-driven injection

If you replace:

    @Autowired
    FooDao fooDao;
with something like:

    @Autowired
    var fooDao;
I'm pretty sure type-driven injection breaks.

[1] https://docs.spring.io/spring/docs/current/spring-framework-...

The proposal only applies to local variables with non-null initializers. I'm pretty sure you can't autowire local variables with Spring, and they don't have initializers anyway.
Yeah, but that's a case where "var" is probably the wrong choice anyways, because of the non-obvious "human type resolution" -- i.e. if I'm a human reading this code, I can't obviously tell the type FooDao, where in simple cases like var path = Paths.get("/foo/bar/bonk") I can.
var isn't a dynamic type. var is a compiler-inferred static type. `var fooDao;` will refuse to compile because the compiler can't infer the type. `var fooDao = new FooDao()` will still have the type FooDao for fooDao, it is just inferred by the compiler instead of being explicitly declared by the programmer.