关于Java10提供的类型推断var的使用注意事项

	/**
	 * We've mitigated this by using simplified error messages when the LHS is
	 * inferred.
	 * 
	 * Examples:(下面的使用方式都是不正确的)
	 * 
	 * Main.java:81: error: cannot infer type for local variable x var x; ^ (cannot
	 * use 'val' on variable without initializer)
	 * 
	 * Main.java:82: error: cannot infer type for local variable f var f = () -> {
	 * }; ^ (lambda expression needs an explicit target-type)
	 * 
	 * Main.java:83: error: cannot infer type for local variable g var g = null; ^
	 * (variable initializer is 'null')
	 * 
	 * Main.java:84: error: cannot infer type for local variable c var c = l(); ^
	 * (inferred type is non denotable)
	 * 
	 * Main.java:195: error: cannot infer type for local variable m var m = this::l;
	 * ^ (method reference needs an explicit target-type)
	 * 
	 * Main.java:199: error: cannot infer type for local variable k var k = { 1 , 2
	 * }; ^ (array initializer needs an explicit target-type)
	 */
	@Test
	public void testVar() {
		/**
		 * var不是关键字,它是保留类型名称 我们可以创建一个名为“var”的变量。 允许使用“var”作为方法名称。 允许使用“var”作为包名。
		 * 但是“var”不能用作类或接口的名称。一句话能用就用不能用改为适应的类型即可
		 * 
		 * 不适用:1.方法参数
		 * 
		 * 2.构造函数参数
		 * 
		 * 3.方法返回类型
		 * 
		 * 4.类成员变量类型
		 */
		// var类型必须初始化
		// var x;

		// 不能用于多变量定义
		// var x = 5, y = 10;

		// var类型不能初始化为null
		// var g = null;

		// var类型数组必须指定具体类型
		// var k0 = { 1, 2 };
		var k = new int[] { 1, 2 };
		// Lambda expression需要一个明确的类型
		// var f = () -> {};

		// 局部变量类型推断(全局变量不能使用),对于开发者来说,这是 JDK10 唯一的真正特性,其他特性都是和Java底层相关的
		var list = new ArrayList<String>();
		// var stream = list.stream();
		// list.add("LLB");

	}

********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

猜你喜欢

转载自blog.csdn.net/weixin_42465125/article/details/88944041
今日推荐