博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Scala中的"null" 和“_”来初始化对象
阅读量:5298 次
发布时间:2019-06-14

本文共 1497 字,大约阅读时间需要 4 分钟。

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 } 
: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 , 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://www.cnblogs.com/hubavyn/p/8058215.html

你可能感兴趣的文章
Redis集群方案Codis部署手册
查看>>
MySQL 第六天
查看>>
python 笔记一
查看>>
pip和easy_install使用方式
查看>>
数据表与简单java类(一对多的关系)
查看>>
博弈论
查看>>
CSS3 - 如何给图片增加内阴影
查看>>
Redis sentinel & cluster 原理分析
查看>>
OD使用教程3(下) - 调试篇03|解密系列
查看>>
我的工作习惯小结
查看>>
Calendar类
查看>>
把word文档中的所有图片导出
查看>>
Spring 自动装配;方法注入
查看>>
浏览器的判断;
查看>>
ubuntu 18.04取消自动锁屏以及设置键盘快捷锁屏
查看>>
Oracle 初始化参数 二三事,随记
查看>>
三维凸包模板
查看>>
zoj 2432(最长递增上升子序列)
查看>>
uva 10791
查看>>
codeforces Round #440 A Search for Pretty Integers【hash/排序】
查看>>