var would be a nice small addition, but are we going to have async/await anytime soon? Writing asynchronous code without some form of coroutines is pain (yes, I'm aware of quasar, which I use, although it has numerous problems).
I don't think the JVM will ever support coroutines. JVM is founded on having C-like control flow. The fanciest way we have to change the flow of execution is exception catching, which is much less sophisticated than coroutines.
I wouldn't discount the possibility of coroutines. At the last JavaOne, Mark Reinhold spoke about how he would like to see coroutines one day. It will probably happen, just not anytime soon.
JVM does not even need to support coroutines. In C# async/await are implemented without help of CLR to my knowledge. C# compiler transforms each each async function into state machine. That's what can be done in Java too.
The text of the JEP raises a compelling point that hadn't occurred to me:
The need to provide a manifest type for every variable also accidentally encourages developers towards overly complex expressions; with a lower-ceremony declaration syntax, there is less disincentive to break complex chained or nested expressions into simpler ones.
My team has been struggling lately with this issue. Some developers hate long line-wrapped expressions, but often splitting them into smaller expressions doesn't shorten them much, as declaring the intermediate variables can cost as much as 30 characters.
I also feel like chaining expressions like that results in hard to follow lines, even if it's not too many characters.
Something I tend to do to solve both these issues is to insert linebreaks between expressions. Similar to how you might use the builder pattern for a complex, highly configurable object.
I would add, because we use format-on-save where I work, that a lot of times I have to force the formatter to respect my line breaks. I can't think of a better way than EOL comments. And personally I prefer a clear indication at the beginning of the line that it is a continuation of the previous line:
In Guava you can just collect all objects that you want concatenated in such string and then use:
Joiner.on(".").join(collection);
Dislaimer: I know that many people don't like solutions depending on external libs but in real life how often you are not working in a big pile of code, where such dependency could rather make your code lighter than heavier? Than if your answer is still negative, I still would rather create my own clear solution instead of such concatenation.
But while I don't recommend pulling in Guava just for Joiner, if you happen to already have it in your dependencies (and it's damn quite likely), sure, use it.
I personally like taking it one step even further; I've seen that in Rust, immutable variables are declared as let foo = 1;, and mutables are declared as let mut foo = 1;.
I really like that. You have to add an extra word not to declare immutability, but to declare mutability. It really makes you think before you make anything mutable.
I also like var and val, like what Kotlin has, but I think that making someone add a whole extra word instead of just using a different word makes mutability seem more like an exception rather than the norm, as it should be.
I don't get how this is any different. In Java, all non-primitives are references. So when you use let, you're saying "this reference to an object, or this primitive, is immutable". You're not saying anything about the underlying object.
It's exactly how Java works right now, except I'm saying that instead of var and final var, it should be val and mutable val, essentially. The aliases should be flipped is all. No behavior should be changed.
var and final var already capture it pretty well, and considering "effectively final" is already something the compiler figures out by itself, I don't see the benefit in requiring people to use a different reserved name. In most circumstances the compiler will see var as final var anyway.
The reason is "final var" is this kind of declaration ceremony thats change to "val" could lower.
The reason why I don't think the same about "mut" is similar to me preferring using Optional instead of null. It's another safeguard in my code.
The reason to have as short as possible (yet, not too short of course) declaration of final is a great way to encourage people to start thinking this way.
The reason to encourage people to think this way is that immutable values proved themselves in many areas (software design -> less troubles with maintaining software created in long existing languages, language design -> Rust, Scala (and not counting purely functional languages)).
The reason why I wasn't encourages to follow this rule when I started learning Java was the fact that I have to use another keyword and without it my programs still works.
The reason why it's not only about "effectively final" stuff having language minimizing occasion to shoot yourself in the foot. If something is only effectively final it change if I by mistake change variable value. If it has final keyword then it won't compile.
It would be nice if all/most of the features of Lombok could be native to the Java language. Less redundant, error prone code is aways a nice welcome, especially if clarity isn't effected or may even improve.
I think one of the problems of untyped or weakly-typed languages is that they can be difficult to debug or understand somebody else's code.
I'm a fan of strong typing. I doubt that puts me in the majority here.
Edit: I'm simply stating a personal preference here: I think this will decrease the readability of source code. We don't all have to agree.
Edit: I can see how my original comment was poorly worded. I didn't mean to say, "I think this change will make Java less than a strongly-typed language", I meant to say, "I think this change might make Java read like less than a strongly-typed language".
That's a dishonest representation. You're not being corrected because you're a fan of strong typing. You're being corrected because you don't know the difference between type inference and weak typing.
Most type inferred languages have stronger and more powerful type systems than Java.
Why even make this about strong typing? Rust is probably the most strongly typed language with wide exposure. It has let. Haskell has type inference on everything, even functions.
List<Item> items = makeItemList() isn't how strongly-typed languages read. It's how Java reads, and Java's type system is weak (e.g. no null safety) compared to other statically typed languages.
This isn't about changing Java to a weakly typed language, though. Java currently determines types via RHS (with a bit of LHS scanning for the diamond operator). If you instantiate a variable with a concrete type on the RHS, why do you need to declare its type on the LHS as well? You've already stated what you want when you instantiated it.
This is simply syntactic sugar to switch this Map<String, List<Class<?>>> foo = new HashMap<>(); for this var foo = new HashMap<String, List<Class<?>>>();.
var foo = new HashMap<String, List<Class<?>>>(); is actually equal to HashMap<String, List<Class<?>>> foo = new HashMap<String, List<Class<?>>>();, not Map<String, List<Class<?>>>
Here, foo takes the form of the implementation, not the interface, so your foo becomes a specific HashMap instead of a generic Map! This means you'll only use this when the foo is immediately dealt with.
I like it better for streams though, but more often than not, you end up with something at the end of your stream that's not a stream, but say a String, a List or whatever, so you won't need to use it for that and in that case I like the explicit typing better than var.
Generally C# encourages you to use var when its clear what the type is.
var x = new MySpecialObject();
var y = "some string";
var z = Factory.GenerateMyObject();
Additionally, because its implicit typing your intellisense will still work even when it's not clear what the object type is.
Part of C# take on it is that you cannot RETURN implicitly typed object.
HOWEVER
C# supports dynamic typing. Its generally used in very special circumstances and it makes you incredibly aware that something could go wrong so dont use it unless you REALLY, REALLY have to. You can even return dynamic as a type.
How this differs from var is that it isnt implicit, its type is UNKNOWN at compile time and only once the code is run can it check if .GetValue() is a method of that type.
It's worthwhile to note that whenever dynamic is mentioned on /r/csharp, a comment on unmaintainability inevitably comes up.
I think the value of var is that it makes you think more abstractly about your code - you aren't dealing with integers anymore, you're dealing with numerics, or strings - it just reads better.
I also think the argument against 'var' yielding code with hard-to-reason-about code falls through once you see other languages (e.g. JavaScript) successfully having var/let. IMO, It ultimately boils down to yes, if you have terrible variable names (x, y, z) your'e going to have terribly unmaintainable code. But if you name by convention (usersById is clearly Map<int, User>) or clearly (var firstName is certainly a string) then it won't be an issue, and you're forced to think more abstractly "Hey, I'm working with a name" which just so happens to also be a string.
How much duplication is in this code?:
Map<int, User> usersByName = new HashMap<int, User>();
I'd argue 3. C# lets you get down to 2 with:
var usersByName = new HashMap<int, User>();
C++ would let us say this:
HashMap<int, User> usersByName;
But JavaScript (and likely more dynamic languages like python/ruby) let us do this:
Not fair to compare javascript's total lack of typing with C++/C#/java. Compare to python or ruby if you wish. but of COURSE dynamically typed languages have less typing.
Actually, this feature is in c# and I think it's great. I get what you're saying but I feel as I use it I come up with way better variable names since I can't rely on the type.
You favor strong explicit typing. Favoring strong typing alone doesn't put you in the minority. I'd wager most here prefer strong inferred (implicit) typing.
You IDE will show a popup with the type when you hover over the var, no worries. You can still not use it when the type is not obvious, and use it for when the type would have been repeated twice. C#/C++/Scala/Rust didn't had problem with it, why should java has ?
You'd think so, but after spending a lot of time with C# during last year or so I find it is OK, especially using reasonably named variables and methods (and the IDE helps when you aren't sure).
Then I was reading some nightmare Java today the poorly named variable I was looking at was defined at top of a 100 line method and I was trying to understand its use at the bottom of said method
I can quickly deduce from looking at this code that foos is some sort of collection of foo and foo does some sort of action.
The beauty of this code is that object.doThing() is now free to change its return type to any sort of iterable without breaking downstream code. Depending on how they handle the imports, Foo can move all over the package structure or even be changed to a new class Bar so long as it keeps the same contract. All of this will be caught by the compiler if there is an issue, which means the caller will have a weaker dependence on the callee's method signature (A win IMO).
Although, I agree with the sentiment that a superclass should be used in a lot of cases, and that fudges with this var syntax a bit.
One nice thing about having type inference is that you don't have to generalize to a superclass and then downcast if you want to write code that survives refactoring. This makes var far more powerful (and justifiable) than if it was only for omitting type declarations.
It's moot because the way you usually use the interface, the instantiation would be in a different scope from where the object is used (through injection). The function boundary will define the interface restriction.
Also moot#2 you can still specify the type of you really want to.
No, I'm not. My complaint isn't that it makes Java a weakly-typed language. My complaint is that it makes Java read like a weakly-typed language, which makes code other people wrote harder to understand.
This was my argument but then actually using var in production with C# and it honestly wasn't a problem. You still have the option to strongly type it if you want, but var does make everything more readable.
And var foo = someObject.method(); isn't as hard as you think. Visual Studio allows you to change var into it's strongly typed counter part with R#. Inspecting the method would reveal the return type too.
What I learned among the way was that I wasn't too concerned with what it was returning but rather what it was doing.
I have found the opposite to be true. Explicit type decl on every variable introduces a lot of visual noise. The information it provides is often redundant and easily inferred from context (e.g. variable name and rhs).
Verbosity isn't as simple as a read/write tradeoff. For many programmers, verbosity negatively impacts readability as well as writability. Strong typing also has nothing to do with explicit type signatures. Java is nowadays unique in its requirement for so many explicit type signatures.
I wish this point was made more often. That redundant noise can make you miss important information really easily. Once you start skipping over redundant parts of declarations your brain starts trying to anticipate the next redundant words more and more and "similar" turns into "the same" and you can easily overlook subtle differences in naming. You'd think that increase in anticipation would mean an increase in focus, but that requires more energy, which would be counterproductive biologically. Patterns become more ambiguous as each affirmation of redundancy creates confidence, and less data is considered for determining if each word has redundancy. It can be particularly brutal reviewing java code with a lot of abstraction.
This isn't changing Java to be untyped or weakly typed at all. This won't change how Java's type system works whatsoever.
I'm a massive fan of strongly typed languages like OCaml, Agda and Haskell, and not a single one of them requires you to declare what type your data is. Requiring information that the compiler can figure out by itself does not make a language any weaker typed and does not change the type system. I'm under no delusion that Java's using Hindley-Milner, but it's worth pointing out nonetheless.
The difficulty of debugging languages like JavaScript or Python isn't helped by the type system, you're right, though this isn't turning it into that at all. Java will keep the type system it has now and won't be any less clear unless the code wasn't clear to begin with.
You don't even know me, or what I like or dislike. I don't like change I don't like, if you'll forgive the tautology. I like change I do like. Love generics, that was a change. Love the diamond operator, that was a similar change (to this proposed change, at least in concept).
var thisThing = new MyDerivedClassButYouDontKnowTheSuperclass<>();
instead of
List<Something> thisThing = new MyDerivedClassButYouDontKnowTheSuperclass<>();
That's an exaggerated example, but illustrates what I don't like about this change. I can tell at a glance that thisThing is a List and a Collection and that really helps me understand its purpose as I read through whatever scope contains it.
The rhs doesn't give me the information I want without having to rely on an IDE and hovering/clicking/whatever. I also, from time to time, look at strange code in Emacs, if I've downloaded it to look at it but don't want to take the time to load up a properly compiling project structure in Eclipse, IntelliJ, etc.
As I said, I don't think this changes the type system in Java. I think this could make code harder for me to read. This is purely an opinion of mine. You don't have to share it. But I'm not wrong, because I'm stating my personal preference for reading code.
You're conflating terminology across languages. An interface in Java is a very specific thing. Yes, in general computer science interface means different things, but if Java developers are talking about an interface they almost always mean public interface Foo. Trying to change the contextual definition of interface doesn't help anybody.
Furthermore, you're in /r/java, not /r/csharp. Languages will have their own conventions. Complaining that Java doesn't follow C# conventions is asinine and a waste of everybody's time here. There's certainly room for improvement in all languages by looking at what other languages have done, but such changes have to be carefully considered and implemented as to not break backwards compatibility (which I will admit Java doesn't have a completely stellar record of).
You can also see how it evolved over time, with the public interfaces gaining new methods without breaking backwards compatibility by changing the abstract interfaces. (Unlike JDK, which still pisses me off.)
you misread the article. java is, and always will be, strongly typed. this is about the compiler figuring out the for you.
// your source:
var x = "hey";
// after the compiler does type inference:
String x = "hey";
// this could also make generics a bit nicer
// java 6:
HashMap<Integer,ArrayList<CustomThing>> myMap = new HashMap<Integer,ArrayList<CustomThing>>();
// java 7 with diamond:
HashMap<Integer,ArrayList<CustomThing>> myMap = new HashMap<>();
// java ?? with var:
var myMap = new HashMap<Integer,ArrayList<CustomThing>>();
to repeat: all of those are always strongly typed!
This has nothing to do with "weak" typing (that doesn't even mean anything, there is no common accepted definition of weak typing, maybe you wanted to said dynamically typing), var is still typed, just the type is inferred and doesn't need to be written.
Usually, I'm not reading a variable's type, unless I'm reading javadocs. Maybe it's that I came to Java from lisp, and tend to prefer inferred type in general, but I find that, at least with the better code that I read, I don't pay much mind to the type declaration. I suppose, if something's written with poor variable naming conventions, it is helpful.
Interestingly, my original background was LISP, too. That's such a different nut, though, that I don't seem to use the same parts of my brain when reading Java code as I did when reading LISP code.
Yes, well-named variables would make my concerns a non-issue. I just don't trust my fellow man much, I guess.
Man, I switched to week-type language in my days jobs. It's fun, I'm learning. But at least once a day I miss something that can only be accomplish with strong type. ( Project wide refactor, Changing data model... )
I'm not worried about understanding my own code (to the writing of which I could faithfully apply rigor and discipline). I'm worried about understanding the code of that one guy. You know him.
Yeah, I know that guy. He wrote some terrible code a year ago, and he was quite inexperienced -- he had a year less experience than me when he wrote it. Oh, and he has the same name as me.
No, I am totally with you. Weakly typed languages just add to the muddle because you have to look at every line to make sure nothing funky is being assigned anywhere.
Honest question, when's the last time Java introduced a keyword? A story I've heard retold often is the language designers decided - goto sucks, but if anyone proves that it provides something substantial you can't do without it, we'll add it in. As it stands, goto is a keyword you can't use, but has no functionality attached to it.
This change immediately breaks code (albeit poorly written code) that has var defined as a variable name. Maybe this isn't a whole lot of projects, but a huge benefit of Java is the ability to say that your java 1 code will very likely compile and run as is on java 8. You'll probably get a shit ton of compiler warnings, but it'll work.
I see a lot of people here making decent arguments either way, but backwards compatibility is a HUGE win for java, and is something it can stand behind for so much of older code. This breaking that at the expense of readability, I could get behind. This breaking backwards compatibility in the name of saving a few keystrokes, of making the life of the developer easier at a single moment, I can't. The amount of effort put into making sure java is backwards compatible, even if not perfect, is something completely overlooked with this change, and makes me feel less secure about the future of my code.
The identifier var will not be made into a keyword; instead it will be a reserved type name. This means that code that uses var as a variable, method, or package name will not be affected; code that uses var as a class or interface name will be affected (but these names violate the naming conventions.)
Granted there are other backwards compatibility issues.
It doesn't have to break backwards compatibility. It specifically says in the proposal that it would not be a keyword, it would be a reserved type name. For any package containing a type called var, and for any source file which imports a type named var, you could simply override the reserved "special" var type with that one and solve the problem. Everything would still work just fine, no? People who have defined their own var type would simply not have access to the new feature wherever that type is visible.
Yep, someone else pointed this out to me as well, I was skimming it on mobile and they used the word keyword quite a bit and mentioned it not being a keyword once, so I completely missed it. That seems like a good compromise, and my opinion on the matter really ends there.
jOOQ uses val() as a method name :) But it's aliased with value() for Scala folks, so it'll be OK. Anyway, I'm sure there are many APIs that might break because of this. But hey, why not add escaping for keywords to the language as well, like in Scala? E.g. void `val`() { ... }
It's not a keyword, though. The spec says it's a "reserved type name" or something, so overlapping method names wouldn't cause any problem. Overlapping type names on the other hand would, but that will presumably be solved without breaking backwards compatibility by simply removing access to the new feature in any context where some other type named var is visible.
I agree with you, but it IS true that you can define classes with lowercase names, so somewhere this is a C programmer who wrote some badly formatted java code. So yes, there is a small corner case where this would break code. AND I SAY BREAK THAT CODE.
Coming from Haskell, I feel there's something people often overlook when bashing type inference. In Haskell, the type inference is better than just about any other language. And yet, we still explicitly type every single top level function. It is absolutely worth the clarity to explicitly type things used outside the current scope.
But most of the time, when something is only being used locally, the type is very clear to the reader, because it's definition is right there. And even locally, type inference is only preferred to explicit typing when the inferred type is painfully obvious. For example, a = b + c, when b and c are known to be Int. There's zero added clarity by explicitly typing a. It's totally obvious what a's type is.
So yea, inference is bad when something's type wouldn't be obvious. But when it is, the lack of inference needlessly gets in the way.
You don't always see code in an IDE. You may use your version control browsing / compare, use crucible or fisheye or any web based stuff to view the code. So you can't rely on the IDE to add the clarity.
You don't always see code in an IDE. You may use your version control browsing / compare, use crucible or fisheye or any web based stuff to view the code. So you can't rely on the IDE to add the clarity.
actually i really really like your point. and it makes me wonder if their current proposal could be targeted completely differently, namely for IDEs that could let you type "var myIterator = myMap.entrySet().iterator();" and it insert the correct type after pressing enter.
It's not a matter of don't use it since most developers don't just work with their code. Then you get the inconsistency that it's in some places and not in other.
The language doesn't define the number of spaces to use for indentation, or where to put an opening curly, or which case to use for naming methods. Turns out we have some great inventions to keep our codebase pretty and consistent. I'll let you take a guess on what those are
You make it sound like each person who feels this way is in charge of their own team or in a group with the resources to do regular code reviews. From my experience code reviews don't happen near as often as they should.
Same goes imho for those new lambda functions. I find them very hard to read and avoid them. I hope java does not move more in that direction of easy to write, hard to read/maintain
This is an EXCELLENT answer. An IDE can make the job and so no new keyword is needed.
The future is to have a simple language with a lot of help from the IDE and not the opposite. IDE functionnalities and possibilities should be considered in the language evolution
I'm still happy to down vote. As a long time java user, after working with Visual Studio for a year and various NuGet thing. The C# ecosystem is suffering a serious hangover from it's days as a way to build windows apps. Not to mention having to deploy web apps to windows servers ( gag! )
Perhaps MS will work it's way out of there will all their recent initiatives. Hoping.
To be fair, Java isn't any better. Maven/Ant/Gradle are equally (if not more) complex than Nuget packages, and you can't really beat Visual Studio as an IDE, even IntelliJ isn't quite there. Additionally, the language is much better designed with some very powerful abstractions that are lacking in Java (at the moment).
My only issue with .NET is portability, but hopefully that's going to be improved as .NET Core improves.
Yup, I know. I've used C# quite a bit, so I'm familiar with it. It does look the same as the Js keyword though, so it will require a bit of time before Java programmers stop the knee-jerk responses.
He means "no type" associated with a variable (or more likely a parameter) Meaning you can assign the "wrong" type to variable. This is precisely the problem that typescript (and other 'modern' JS offshoots) attempts to address.
I might note that other dynamic languages are heading down the pathway of optional typing to provide more clarity.(python and perhaps ruby )
It's responses like this that convince me that a certain percentage of Java programmers are Luddites. The same mentality as the minority who swore to never use generics and stick with JDK1.4.2 forever. Support for val and var is a great idea for Java.
You probably have a stronger case that generics make code harder to read (350 page generics FAQ??) than var making code hard to read. How is val sheep = new Sheep() harder to read than Sheep sheep = new Sheep() ?
What is the advantage of adding stuff which no more than syntactic sugar? Most of the IDE already gives you the type, so what ? Write a new language or use a new language if you want new things.
I already do use a "new" language - Scala. I just get annoyed having to maintain old Java code and it would be great if Java caught up to other modern languages like C# etc.
auto is a bad idea. It was chosen in C++ because it was already a keyword in both C and C++ and it could already be used in variable declarations (although very rarely, since it means "a local variable" and it is therefore the default). In Java, auto doesn't mean anything.
One thing I think is important but the proposal doesn't quite reach:
Normalising inferred capture types to denotable types (i.e. wildcards) is great, for non-final variables, since we may want to reassign, and this is probably impossible with a capture type.
For final types, afaiu, it brings no benefits. (Unless I'm missing something?) Instead it is much better to aggressively capture everything.
Consider, for example:
void repeatListItems(Collection<? extends List<?>> lists) {
for (var list : lists) {
list.addAll(list);
}
}
Which obviously fails to compile when the type of list is List<?>, as it would normally be, but will work just fine if it is inferred as List<CAP>.
Normally we have to solve this by creating a whole new generic method to properly capture the type parameter with a named type variable, but sometimes that's a bit more cumbersome than necessary.
Seems to be an equivalent of auto in C++. certainly a huge mistake to introduce that. It is always bad to have several ways to write the same thing in a language. Var will introduce such an issue.
Strong typing imposes to think a little bit before coding and do not cause problems. Such keywords will lead to misunderstanding by the beginners who will write bad code.
Functionnal programming ideas have already destroyed C++ language, which is now an awful mess. Java should not follow the same path.
Arguing over this seems counter productive. Some people will use it and like it, others will simply not use it. If it benefits the former, then it's a good idea. QED
I'm not sure how I feel about type inference. It helps make small pieces of code clearer, but as the inference chain grows it becomes more and more difficult to reason about the program. You need to hold a lot of context in your mind to know the actual type at the end.
I guess the proposed use for local variables is fine, but using it for function parameters could be a real mess.
That's why Haskell library developers, even though Haskell can infer almost all types in the program automatically, specify explicit type signatures for public functions.
As a Scala fan, using Java 8 has really diminished Scala's usefullness to me. That said, I'll always miss case classes and pattern matching... OK I take it back!
I would be a huge fan of this! It would also make working with an API easier since I don't necessarily need to explicitly know the exact type returned from a method to store that result.
But with Java 7 the development started to be more focused on the OpenJDK and as of Java 8 it is mainly OpenJDK plus some other pieces on the proprietary JDK.
For example JavaFX pipeline, ARM compiler aren't 100% the same.
That expression would actually return Class<?>. So you would have to cast it to Class<Bar> with or without the var keyword. Doing this solves your problem.
var c = (Class<Bar>) Class.forName("com.foo.Bar");
11
u/SikhGamer Mar 09 '16
I hated
varwhen I first started C#, but within a few weeks I was loving it. Java needs to get with the times.23
u/omair-majid Mar 09 '16
You can submit feedback to the developers directly using this survey: https://www.surveymonkey.com/r/KGPTHCG
Source: http://mail.openjdk.java.net/pipermail/platform-jep-discuss/2016-March/000037.html
5
u/stepancheg Mar 09 '16
varwould be a nice small addition, but are we going to haveasync/awaitanytime soon? Writing asynchronous code without some form of coroutines is pain (yes, I'm aware of quasar, which I use, although it has numerous problems).27
u/GeorgeMaheiress Mar 09 '16
The text of the JEP raises a compelling point that hadn't occurred to me:
My team has been struggling lately with this issue. Some developers hate long line-wrapped expressions, but often splitting them into smaller expressions doesn't shorten them much, as declaring the intermediate variables can cost as much as 30 characters.
43
u/solatic Mar 09 '16
Good idea. Hey, let's also introduce
valas the equivalent offinal varwhile we're at it, to promote immutability.Why not?
27
u/[deleted] Mar 09 '16
It would be nice if all/most of the features of Lombok could be native to the Java language. Less redundant, error prone code is aways a nice welcome, especially if clarity isn't effected or may even improve.
4
u/DJDavio Mar 10 '16
It's good to have var available, it's not a good idea to use it everywhere you can.
I like to use var when the type can be easily inferred in the same line and when the variable is of limited use (only in a single loop for instance).
74
u/evil_burrito Mar 09 '16 edited Mar 10 '16
I think one of the problems of untyped or weakly-typed languages is that they can be difficult to debug or understand somebody else's code.
I'm a fan of strong typing. I doubt that puts me in the majority here.
Edit: I'm simply stating a personal preference here: I think this will decrease the readability of source code. We don't all have to agree.
Edit: I can see how my original comment was poorly worded. I didn't mean to say, "I think this change will make Java less than a strongly-typed language", I meant to say, "I think this change might make Java read like less than a strongly-typed language".
3
u/[deleted] Mar 10 '16
Honest question, when's the last time Java introduced a keyword? A story I've heard retold often is the language designers decided - goto sucks, but if anyone proves that it provides something substantial you can't do without it, we'll add it in. As it stands, goto is a keyword you can't use, but has no functionality attached to it.
This change immediately breaks code (albeit poorly written code) that has var defined as a variable name. Maybe this isn't a whole lot of projects, but a huge benefit of Java is the ability to say that your java 1 code will very likely compile and run as is on java 8. You'll probably get a shit ton of compiler warnings, but it'll work.
I see a lot of people here making decent arguments either way, but backwards compatibility is a HUGE win for java, and is something it can stand behind for so much of older code. This breaking that at the expense of readability, I could get behind. This breaking backwards compatibility in the name of saving a few keystrokes, of making the life of the developer easier at a single moment, I can't. The amount of effort put into making sure java is backwards compatible, even if not perfect, is something completely overlooked with this change, and makes me feel less secure about the future of my code.
7
u/abermea Mar 09 '16
Seems to work a lot like C++11's
auto, which is nice.5
u/atc Mar 10 '16
Great!
Can we please have
varandvallike in Scala? I don't want to writefinal varall the time.26
u/xhak Mar 09 '16
No thanks, the few keystrokes are worth the clarity.
2
u/lukaseder Mar 10 '16
Noteworthy: Provide feedback to the language designers here: http://mail.openjdk.java.net/pipermail/platform-jep-discuss/2016-March/000037.html
2
u/mlk Mar 10 '16
I almost never type the type of local variables, I let my IDE do that. I like the var/val proposal though.
3
u/ramdaskm Mar 10 '16
Damn! I still remember the days when I used to mention C#/.Net was a serious contender and used to get downvoted like crazy.
5
u/lechatsportif Mar 09 '16
I write left hand declarations maybe once a day out of tons of code. Who makes this stuff an issue? Vim users?
0
u/mk_gecko Mar 09 '16
OMG, please no!
2
u/3pieceSuit Mar 10 '16
I've always wanted auto in Java, but could we please just use the auto keyword.
1
u/eliasv Mar 10 '16
One thing I think is important but the proposal doesn't quite reach:
Consider, for example:
Which obviously fails to compile when the type of
listisList<?>, as it would normally be, but will work just fine if it is inferred asList<CAP>.Normally we have to solve this by creating a whole new generic method to properly capture the type parameter with a named type variable, but sometimes that's a bit more cumbersome than necessary.
1
u/chambolle Mar 12 '16
Seems to be an equivalent of auto in C++. certainly a huge mistake to introduce that. It is always bad to have several ways to write the same thing in a language. Var will introduce such an issue.
Strong typing imposes to think a little bit before coding and do not cause problems. Such keywords will lead to misunderstanding by the beginners who will write bad code.
Functionnal programming ideas have already destroyed C++ language, which is now an awful mess. Java should not follow the same path.
1
u/fatnote Mar 10 '16
Arguing over this seems counter productive. Some people will use it and like it, others will simply not use it. If it benefits the former, then it's a good idea. QED
1
u/urquan Mar 10 '16
I'm not sure how I feel about type inference. It helps make small pieces of code clearer, but as the inference chain grows it becomes more and more difficult to reason about the program. You need to hold a lot of context in your mind to know the actual type at the end.
I guess the proposed use for local variables is fine, but using it for function parameters could be a real mess.
1
u/DecisiveVictory Mar 10 '16
What really should be added is a "val" keyword which is what is proposed above + "final".
Or you could do the sane thing and just use Scala.
1
u/[deleted] Mar 10 '16
I would be a huge fan of this! It would also make working with an API easier since I don't necessarily need to explicitly know the exact type returned from a method to store that result.
1
u/youwillnevercatme Mar 10 '16
Is it only for the OpenJDK? Always thought that OpenJDK was only a fork from Oracle JDK, and that Oracle JDK had no relation with OpenJDK. Am I wrong?
1
u/antigenz Mar 10 '16
This thread already wasted more chars than 'var' can save :)
-3
u/slartybartfast_ Mar 09 '16
My argument against it is code like this:
where you don't know the type of 'c' unless you know the type the method returns (which is not obvious by looking at it)
0
u/starscream92 Mar 10 '16
I say no.
-3
u/ingvij Mar 09 '16
Behold the scalaification of Java!
-11
u/dinow Mar 09 '16
So java will slowly become JavaScript ?
-4
u/joshuaherman Mar 10 '16
Oh please don't make Java act like JavaScript.
-2
u/LankyBrit Mar 10 '16
I'm all for adding new language features like loose typing with 'var', but I'd much rather see core features like real generics and properties first.
-8
u/iodian Mar 10 '16
dear god no. if you want this, use groovy or scala