Issue
One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?
Solution
There is none. Alas, you have to type out the full type name.
Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.
Edit: 6 years after being posted, to collect some of the comments from below:
The reason C# has the
varkeyword is because it's possible to have Types that have no name in .NET. Eg:var myData = new { a = 1, b = "2" };In this case, it would be impossible to give a proper type to
myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.varis not the same asdynamic.variables are still 100% statically typed. This will not compile:var myString = "foo"; myString = 3;varis also useful when the type is obvious from context. For example:var currentUser = User.GetCurrent();I can say that in any code that I am responsible for,
currentUserhas aUseror derived class in it. Obviously, if your implementation ofUser.GetCurrentreturn an int, then maybe this is a detriment to you.This has nothing to do with
var, but if you have weird inheritance hierarchies where you shadow methods with other methods (egnew public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
class Foo { public void Non() {} public virtual void Virt() {} } class Bar : Foo { public new void Non() {} public override void Virt() {} } class Baz { public static Foo GetFoo() { return new Bar(); } } var foo = Baz.GetFoo(); foo.Non(); // <- Foo.Non, not Bar.Non foo.Virt(); // <- Bar.Virt var bar = (Bar)foo; bar.Non(); // <- Bar.Non, not Foo.Non bar.Virt(); // <- Still Bar.VirtAs indicated, virtual methods are not affected by this.
No, there is no non-clumsy way to initialize a
varwithout an actual variable.var foo1 = "bar"; //good var foo2; //bad, what type? var foo3 = null; //bad, null doesn't have a type var foo4 = default(var); //what? var foo5 = (object)null; //legal, but go home, you're drunkIn this case, just do it the old fashioned way:
object foo6;
Answered By - Mike Caron Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.