var 和 val 下划线初始化的区别 [英] Difference between underscore initialization of var and val

查看:31
本文介绍了var 和 val 下划线初始化的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 val x: Int = _ 不编译但 var x: Int = _ 编译?

Why does val x: Int = _ not compile but var x: Int = _ does?

我收到错误:未绑定占位符参数.

推荐答案

在这种情况下,_ 的意思是我稍后会初始化它,在此期间填写任何合理的默认值".由于您无法重新分配 val,因此这没有任何意义.

In this context, _ means "I will initialize this later, just fill in whatever the sensible default is in the meantime". Since you can't reassign a val, this doesn't make sense.

对于相同的功能——为了获得合理的默认值——对于 val,你可以使用

For the same functionality--to get the sensible default--for a val, you can use

val x: Int = null.asInstanceOf[Int]

这篇关于var 和 val 下划线初始化的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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