Scala中的"null" 和“_”来初始化对象

Alternatives

Use null as a last resort. As already mentioned, Option replaces most usages of null. If you using null to implement deferred initialisation of a field with some expensive calculation, you should use a lazy val.

Canonical initialisation to null

That said, Scala does support null. I personally use it in combination with Spring Dependency Injection.

Your code is perfectly valid. However, I suggest that you use var t: T = _ to initialize t to it's default value. If T is a primitive, you get the default specific to the type. Otherwise you get null.

Not only is this more concise, but it is necessary when you don't know in advance what T will be:

scala> class A[T] { var t: T = _ } defined class A scala> new A[String].t res0: String = null scala> new A[Object].t res1: java.lang.Object = null scala> new A[Int].t res2: Int = 0 scala> new A[Byte].t res3: Byte = 0 scala> new A[Boolean].t res4: Boolean = false scala> new A[Any].t res5: Any = null

Advanced

Using var t: T= null is a compile error if T is unbounded:

scala> class A[T] { var t: T = null } <console>:5: error: type mismatch; found : Null(null) required: T class A[T] { var t: T = null }

You can add an implicit parameter as evidence that T is nullable -- a subtype of AnyRef not a subtype of NotNull This isn't fully baked, even in Scala 2.8, so just consider it a curiousity for now.

scala> class A[T](implicit ev: Null <:< T) { var t: T = null } defined class A

参考链接:

https://stackoverflow.com/questions/2440134/is-this-the-proper-way-to-initialize-null-references-in-scala

 



转载于:https://www.cnblogs.com/hubavyn/p/8058215.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值