inferred type_您最终可以使用var在Java中声明Inferred Type局部变量-这就是为什么它很棒...

inferred type

by javinpaul

由javinpaul

您最终可以使用var在Java中声明Inferred Type局部变量-这就是为什么它很棒 (You can finally declare Inferred Type local variables in Java with var — here’s why that’s awesome)

Hello everyone! In this article, I’ll discuss new features of Java 10. Specifically, I am going to talk about probably the most popular and most useful: the introduction of the var keyword in Java. Well, it’s not really a keyword — but I’ll tell you about it later.

大家好! 在本文中,我将讨论Java 10的新功能具体地说,我将讨论最流行和最有用的方法: Java中var关键字引入。 好吧,它并不是真正的关键字,但是稍后我会告诉您。

终于…… (At long last…)

Finally, Java has gotten the var keyword to declare local variables. This allows you to declare a variable without its type. For example, instead of doing this:

最终,Java获得了var关键字来声明局部变量。 这使您可以声明一个没有类型的变量。 例如,不要这样做:

String str = “Java”

String str = “Java”

you can now just say this:

您现在可以这样说:

var str = “Java”.

var str = “Java”.

This may not sound like much to gain when you’re declaring a String or an int variable, but think about complex types with generics, for example. This will surely save a lot of typing, and will also improve the readability of the code.

当您声明一个String或一个int变量时,这听起来可能没有什么好处,但是例如考虑泛型的复杂类型。 这肯定会节省很多输入时间,也将提高代码的可读性。

一点背景 (A little background)

Java developers have long been complaining about boilerplate code and the ceremonies involved while writing code. Many things which take just 5 minutes in languages like Python, Groovy, or JavaScript can take more than 30 minutes in Java due to its verbosity.

长期以来,Java开发人员一直在抱怨样板代码以及编写代码时涉及的仪式。 由于冗长,许多语言(如PythonGroovyJavaScript)仅需5分钟,而Java则需要30分钟以上。

If you have coded in Scala, Kotlin, Go, C# or any other JVM language, then you know that they all have some kind of local variable type inference already built into the language.

如果您使用Scala,Kotlin,Go,C#或任何其他JVM语言进行编码,那么您就会知道它们都已经在该语言中内置了某种局部变量类型推断。

For example, JavaScript has let and var, Scala and Kotlin have var and val, C++ has the auto, C# has var, and Go supports this by declaration with the := operator.

例如,JavaScript具有letvarScalaKotlin具有varval ,C ++具有auto ,C#具有var,而Go通过使用:=运算符进行声明来支持此功能。

Until Java 10, Java was the only language which didn’t have local variable type inference or support for the var keyword.

Java 10之前 ,Java是唯一没有局部变量类型推断或不支持var关键字的语言。

Though type inference was improved a lot in Java 8 with the introduction of the lambda expression, method references, and Streams, local variables still needed to be declared with proper type. But that’s now gone! Java 10 has a feature, JEP 286: Local-Variable Type Inference, which will allow declaring local variables without type information and by just using the var keyword.

尽管在Java 8中通过引入lambda表达式,方法引用和Streams大大改进了类型推断,但是仍然需要使用适当的类型声明局部变量。 但是,现在已经消失了! Java 10具有JEP 286:Local-Variable Type Inference功能 该功能将允许声明局部变量而无需类型信息,而只需使用var关键字即可。

Let’s take a closer look.

让我们仔细看看。

Java 10 var关键字示例 (Java 10 var keyword examples)

Here are some examples of Java 10's var keyword:

以下是Java 10的var关键字的一些示例:

var str = "Java 10"; // infers String
var list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream(); // infers Stream<String>

As I said, at this point you may not fully appreciate what var is doing for you. But look at the next example:

就像我说的,在这一点上,您可能还不完全了解var为您所做的事情。 但是,请看下一个示例:

var list = List.of(1, 2.0, "3")

Here, the list will be inferred into List<? extends Serializable & Comparable&lt;..>> which is an intersection type, but you won’t have to type the full type information. var makes the code much easier to write and read in this case.

在这里,列表将被推断为List <? 扩展了Serializable&Comparable&l t .. >>,它是一个交叉类型,但是您不必键入完整的类型信息。 在这种情况下,var使代码更易于编写和读取。

In next section, we’ll see some more examples that’ll help you learn how to write concise code using var in Java 10.

在下一节中,我们将看到更多示例,这些示例将帮助您学习如何在Java 10中使用var编写简洁的代码。

在Java中使用var关键字编写简洁的代码 (Writing concise code using the var keyword in Java)

The use of the var reserve word also makes your code concise by reducing duplication — for example, the name of the Class which comes on both the right and left-hand side of assignments as shown in the following example:

使用var保留字还可以通过减少重复来使代码简洁—例如,类的名称出现在赋值的左右两侧,如以下示例所示:

ByteArrayOutputStream bos = new ByteArrayOutputStream();

Here ByteArrayOutputStream repeats twice, and we can eliminate that by using the var feature of Java 10 as shown below:

这里ByteArrayOutputStream重复两次,我们可以通过使用Java 10的var功能来消除这种情况,如下所示:

var bos = new ByteArrayOutputStream();

We can do similar things while using try-with-resource statements in Java, for example this

我们可以在Java中使用try-with-resource语句时做类似的事情,例如

try (Stream<Book> data = dbconn.executeQuery(sql)) {    return data.map(...) .filter(...) .findAny(); }

can be written as follows:

可以写成如下:

try (var books = dbconn.executeQuery(query)) {   return books.map(...) .filter(...) .findAny(); }

These are just a few examples. There are a lot of places where you can use var to make your code more concise and readable, many of which you can see on Sander’s Pluarlsight course What’s New in Java 10.

这些只是几个例子。 在很多地方都可以使用var来使代码更简洁明了,您可以在Sander的Pluarlsight课程“ Java 10的新功能”中看到很多地方。

It’s a paid course but you can check out this 10-day free trial.

这是一个付费课程,但您可以查看此10天免费试用

For those programmers who have used Groovy or Scala, the introduction of var makes it seem like Java is going the Scala way…but only time will tell.

对于那些使用GroovyScala的程序员来说,var的引入使Java似乎正朝着Scala的方向发展……但是只有时间会证明一切。

For now, we can just be happy that var makes it easier to declare a complex local variable in Java 10.

现在,我们可以很高兴地看到var使在Java 10中声明一个复杂的局部变量更加容易。

And do note: the local variable type inference of the Java 10 var keyword can only be used to declare local variables (for example, any variable inside the method body or code block).

并注意:Java 10 var关键字的局部变量类型推断只能用于声明局部变量 (例如,方法主体或代码块内的任何变量)。

您可以使用var在Java中声明成员变量吗? (Can you use var to declare member variables in Java?)

You cannot use var to declare member variables inside the class, method formal parameters or return type of methods.

不能使用var在类,方法形式参数或方法的返回类型内声明成员变量。

For example, this example of var is OK:

例如,此示例的var是可以的:

public void aMethod(){ var name = "Java 10"; }

But, following example is NOT OK:

但是,以下示例不正确:

class aClass{   var list; // compile time error }

So, even though this new Java 10 feature is eye-catching and looks good, it still has a long way to go. Still, you can start using it to further simplify your code. Less boilerplate code always means better and more readable code.

因此,即使这个新的Java 10功能引人注目并且看起来不错,它仍有很长的路要走。 不过,您可以开始使用它来进一步简化代码。 更少的样板代码始终意味着更好和更易读的代码。

关于这个新的var关键字的要点 (Important points about this new var keyword)

Now that you know that you can declare local variables without declaring the type in Java 10, it’s time to learn a few important things about this feature before you start using it in your production code:

既然您知道可以在Java 10中声明局部变量而无需声明类型,那么现在就开始学习有关此功能的一些重要知识,然后再在生产代码中使用它:

1. This feature is built under JEP 286: Local-Variable Type Inference and was authored by none other than Brian Goetz. He’s the author of Java Concurrency in Practice, one of the most popular books for Java developers.

1.此功能是在JEP 286:局部变量类型推断下构建的,由Brian Goetz撰写。 他是Java Concurrency in Practice的作者,这是Java开发人员最受欢迎的书籍之一。

2. The var keyword allows local variable type inference, which means the type for the local variable will be inferred by the compiler. Now you don’t need to declare it.

2. var关键字允许本地变量类型推断,这意味着对于该类型的局部变量会被编译器推断。 现在,您无需声明它。

3. The local variable type inference or Java 10 var keyword can only be used to declare local variables, for example inside methods, on initializers code block, indexes in the enhanced for loop, lambda expressions, and local variables declared in a traditional for loop.

3.局部变量类型推断或Java 10 var关键字只能用于声明局部变量 ,例如在初始化程序代码块上的方法内部, 增强的for循环中的索引, lambda表达式以及传统的for循环中声明的局部变量。

You cannot use it for declaring formal variables and return types of methods, for declaring member variables or fields, on constructor formal variables, and any other kind of variable declaration.

您不能将其用于声明形式变量和方法的返回类型,声明成员变量或字段,构造函数形式变量以及任何其他类型的变量声明。

4. Despite the introduction of var, Java is still a statically typed language and there should be enough information to infer the type of the local variable. If not, the compiler will throw an error.

4.尽管引入了var,但Java仍然是一种静态类型的语言,应该有足够的信息来推断局部变量的类型。 否则,编译器将抛出错误。

5. The var keyword is similar to the auto keyword of C++, var of C#, JavaScript, Scala, Kotlin, def of Groovy and Python (to some extent), and the : = operator of the Go programming language.

5. var关键字类似于C ++的auto关键字,C#的var, JavaScriptScalaKotlinGroovyPython的 def(在某种程度上)以及Go编程语言的:=运算符。

6. One important thing to know is that, even though var looks like a keyword, it’s not really a keyword. Instead, it is a reserved type name. This means that code that uses var as a variable, method, or package name will not be affected.

6.要知道的重要一件事是,即使var看起来像一个关键字,但它并不是真正的关键字。 相反,它是保留的类型名称。 这意味着使用var作为变量,方法或程序包名称的代码将不受影响。

7. Another thing to note is that code that uses var as a class or interface name will be affected by this Java 10 change. But as JEP says, these names are rare in practice, since they violate usual naming conventions.

7.要注意的另一件事是,将var用作类或接口名称的代码将受到此Java 10更改的影响。 但是正如JEP所说,这些名称在实践中很少见,因为它们违反了通常的命名约定。

8. The immutable equivalent of local variables or final variables val and let is not yet supported in Java 10.

8. Java 10尚不支持局部变量或最终变量val和let的不变形式

结语 (Wrapping up)

That’s all about the var in Java 10! It’s an interesting Java 10 feature, which allows you to declare local variables without declaring their type. This will also help Java developers pick up other languages quickly, like Python, Scala, or Kotlin, because they heavily use var to declare mutable variables and val to declare immutable local variables.

这就是Java 10中var的全部内容 这是Java 10的一项有趣功能,它允许您声明局部变量而无需声明其类型。 这也将帮助Java开发人员快速使用其他语言,例如PythonScalaKotlin ,因为他们大量使用var声明可变变量和val声明不变的局部变量。

Even though JEP 286: Local-Variable Type Inference only supports var and not val, it is still useful and feels more like coding Scala in Java.

即使JEP 286:局部变量类型推断仅支持var而不支持val ,它仍然很有用,感觉更像是用Java编写Scala。

进阶学习 (Further Learning)

What’s New in Java 10 by Sander Mak Style Guidelines for Local Variable Type Inference in Java JEP 286: Local-Variable Type Inference 10 Things Java Developer Should learn in 2018 The Complete Java MasterClass to learn Java Better

Sander Mak在Java 10中的新增功能 Java JEP 286中的 本地变量类型推断的样式指南 :本地变量类型推断 Java开发人员应在2018年学习的10件事 完整的Java MasterClass可以更好地学习Java

Thanks for reading this article. If you like this new Java 10 feature, then please share with your friends and colleagues.

感谢您阅读本文。 如果您喜欢此Java 10新功能,请与您的朋友和同事分享。

If you have any questions or feedback, please drop a note and stay tuned for more Java 10 tutorials and articles here.

如果您有任何疑问或反馈,请在此处留下注释并继续关注更多Java 10教程和文章。

Originally published at javarevisited.blogspot.com on March 27, 2018.

最初于2018年3月27日发布在javarevisited.blogspot.com上。

翻译自: https://www.freecodecamp.org/news/you-can-finally-declare-local-variables-in-java-with-var-heres-why-that-s-awesome-4418cb7e2da3/

inferred type

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值