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



最新文章

  1. POJ 1459:Power Network(最大流)
  2. 翻译-高效DevOps的10项实践
  3. Windows Phone 8.1中AppBarToggleButton的绑定问题
  4. CoreGraphics相关方法
  5. LR结果分析——TPS和吞吐率
  6. U盘做启动盘后,如何恢复原始容量
  7. Java笔试题集锦
  8. CentOS+OpenCV图像的读入、显示
  9. 【前端】:jQuery实例
  10. iterator_category
  11. IO&amp;&amp;Serize 利用线程Thread.Sleep实现&quot;自动输出&quot;
  12. pandas.DataFrame.describe 官方文档翻译percentile_width,percentiles,include, exclude
  13. 并查集的Java实现
  14. AutoMapper自动映射
  15. 那些IT行业的经典定律
  16. hdu 1010 走到终点时刚好花掉所有时间 (DFS + 奇偶性剪枝 )
  17. WordPress网站搬家全过程 亲身体验WordPress搬家,总结几点
  18. latex之转置符号
  19. mapply
  20. 你正在从一个声称代表如下的证书颁发机构安装证书 alipay truest network,希望能知道程序是怎么实现的或相关资料

热门文章

  1. 洛谷 P1313 计算系数 解题报告
  2. UVA.10791 Minimum Sum LCM (唯一分解定理)
  3. android中的style部分属性值介绍 --zz
  4. 解题:JSOI 2016 最佳团体
  5. Camera ISO、快门、光圈、曝光这几个概念
  6. 翻译: 星球生成 II
  7. soj1036. Crypto Columns
  8. phpunit安装出错的原因及解决办法
  9. element-UI 表单图片判空验证问题
  10. Python练习-装饰器版-为什么我的用户总被锁定