在字段声明中使用var [英] Use var in field declaration

查看:122
本文介绍了在字段声明中使用var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,从Java 9开始,我们可以使用var声明局部变量:

So starting in Java 9, we can use var to declare local variables:

var s = "cool";

有什么方法可以在声明字段时使用类似的构造?

is there a way to use a similar construct when declaring fields?

class Container {
  final var s = "cool"; // does not compile tmk
}

从我的判断来看,

看起来并不像.

doesn't seem like it from what I can tell.

推荐答案

有什么方法可以在声明字段时使用类似的构造?

is there a way to use a similar construct when declaring fields?

不.

根据 JEP 286:局部变量类型推断:

这种处理将仅限于带有初始值设定项的局部变量,增强的for循环中的索引以及在传统的for循环中声明的局部变量;它将 不适用于 方法形式,构造函数形式,方法返回类型,字段,捕获形式或任何其他类型的变量声明. /p>

This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals or any other kind of variable declaration.

这篇关于在字段声明中使用var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆