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开发人员一直在抱怨样板代码以及编写代码时涉及的仪式。 由于冗长,许多语言(如Python , Groovy或JavaScript)仅需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具有letvar , Scala和Kotlin具有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.

对于那些使用Groovy或Scala的程序员来说,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, JavaScript , Scala , Kotlin , Groovy和Python的 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开发人员快速使用其他语言,例如Python , Scala或Kotlin ,因为他们大量使用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

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

  1. 在Java中声明一个unsigned int

    本文翻译自:Declaring an unsigned int in Java Is there a way to declare an unsigned int in Java? 有没有办法在Jav ...

  2. java 全局数组_如何在Java中声明全局数组?

    我有一个程序在Java中乘以两个矩阵.我在全局错误声明中发现了一些错误. 这里是我的代码如何在Java中声明全局数组? import java.util.Scanner; /**WAP in Java ...

  3. cloning java_深入浅出Java中的clone克隆方法,写得太棒了!

    作者:张纪刚 blog.csdn.net/zhangjg_blog/article/details/18369201/ 2019-03-24 10:33:04 Java中对象的创建 clone 顾名思 ...

  4. 深入浅出Java中的clone克隆方法,写得太棒了!

    作者:张纪刚 blog.csdn.net/zhangjg_blog/article/details/18369201/ Java中对象的创建 clone 顾名思义就是 复制 , 在Java语言中, c ...

  5. Java中的全局变量和局部变量——简单区别

    全局变量 Java中不能定义全局变量,在一个类中的公共.静态变量就相当于这个类的全局变量. 这使得全局变量被封装在了类里,保证了安全性. 局部变量 Java中方法体或某个代码块中声明的变量被称为局部变 ...

  6. java中声明内部类变量,java – 从内部类中访问变量(dialogView),需要声明final

    我正在尝试创建一个带有布局"是"或"否"的警告对话框.我想通过单击"否"按钮但是对话框View.dismiss()来关闭对话框;有错误. 这 ...

  7. java中怎么声明常量_如何在Java中声明一个常量

    为了达到上述目的,您可以在Java 5及更高版本中使用enumtypes. 这是types安全的. A是一个实例variables. (如果它有静态修饰符,那么它就成为一个静态variables.)常 ...

  8. java 循环里声明变量赋值_在Java中声明变量外部Foreach循环

    有人可以请赐教我以下事项: public class Loopy { public static void main(String[] args) { int[] myArray = {7,6,5,4 ...

  9. java中的全局变量和局部变量

    一.全局变量 全局变量又称为成员变量,其中实例变量.类变量.常量都属于成员变量. Java类的成员变量包括:1.static关键字修饰的变量,称为静态变量(类变量):2.没有static关键字修饰的变 ...

最新文章

  1. python进行数据分析 kindle_利用Python进行数据分析
  2. Memcache缓存系统原理
  3. 百度经验怎么赚钱之练就三星经验,轻松布局流量入口。
  4. 利用Runtime修改UIdatePicker的字体颜色
  5. 学习笔记之数据可视化(二)—— 页面布局(下)
  6. 内存颗粒和闪存颗粒的区别_NAND Flash闪存颗粒与SSD知识深度解析
  7. 【Flink】Flink 1.10之改进的TaskManager内存模型与配置
  8. shell监控Nginx服务是否存在的脚本
  9. qml中使用combobox实现多级菜单_Excel教程:还不会做Excel三级下拉菜单?其实它跟复制粘贴一样简单...
  10. 【NOIP2010】【Luogu1540】机器翻译
  11. CentOS安装MySQL及其使用(总结整理)
  12. 稳定性思考-强弱依赖
  13. [jQuery]使用jQuery.Validate进行客户端验证(初级篇)——不使用微软验证控件的理由...
  14. ListView分页操作
  15. Ubuntu 16.04.5 (x86_64)下安装CUDA10 for 深度学习
  16. Substance Painter TDR issue TDR问题
  17. Windows10开机进不了BIOS的解决办法
  18. 转载收藏 常用数学符号的读法及其含义
  19. AI芯片:寒武纪ShiDianNao结构分析
  20. System.IO.FileNotFoundException: Could not load file or assembly ‘System.Data.SQLite.dll‘ or one of

热门文章

  1. 用scratch编写打地鼠游戏
  2. 写技术博客的一些心得体会
  3. c# WindowsForm上使用Panel制作画板的一些小功能
  4. 标梵互动信息解说关于CSS-in-JS: 使用及优缺点
  5. 开热点给电脑消耗大吗_用手机热点上电脑是不是比手机用流量更费一些?
  6. Github-谷歌插件gitzip(加速器-不用再忍受几十kb/s的煎熬了)
  7. java在win8闪退_win8.1应用闪退
  8. 白话斯坦福机器学习课程-CS229 - 监督学习应用:梯度下降
  9. alertmanager集群莫名发送resolve消息的问题探究
  10. 兔子繁殖问题(斐波那契数)