加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – NotNull tr??ait在2.8中是如何工作的,有没有人实际使用

发布时间:2020-12-16 09:13:28 所属栏目:安全 来源:网络整理
导读:trait NotNull {} 我一直在试图看看这个特质如何保证一些东西不为空,我无法理解: def main(args: Array[String]) { val i = List(1,2) foo(i) //(*)}def foo(a: Any) = println(a.hashCode)def foo(@NotNull a: Any) = println(a.hashCode) //compile error
trait NotNull {}

我一直在试图看看这个特质如何保证一些东西不为空,我无法理解:

def main(args: Array[String]) {
  val i = List(1,2) 
  foo(i) //(*)
}

def foo(a: Any) = println(a.hashCode)

def foo(@NotNull a: Any) = println(a.hashCode) //compile error: trait NotNull is abstract

def foo(a: Any with NotNull) = println(a.hashCode) //compile error: type mismatch at (*)

和:

val i = new Object with NotNull //compile-error illegal inheritance

显然有一些特殊的编译器处理过程,因为这样编译:

trait MyTrait {}

def main(args: Array[String]) {
  val i: MyTrait = null
  println(i)
}

而这不是:

def main(args: Array[String]) {
  val i: NotNull = null //compile error: found Null(null) required NotNull
  println(i)
}

编辑:没有什么可以在Scala的编程中找到

解决方法

尝试和错误:

scala> class A extends NotNull
defined class A

scala> val a : A = null
<console>:5: error: type mismatch;
 found   : Null(null)
 required: A
       val a : A = null
                   ^

scala> class B
defined class B

scala> val b : B = null
b: B = null

这只适用于Scala 2.7.5:

scala> new Object with NotNull
res1: java.lang.Object with NotNull = $anon$1@39859

scala> val i = new Object with NotNull
i: java.lang.Object with NotNull = $anon$1@d39c9f

和Scala语言参考:

If that member has a type which
conforms to scala.NotNull,the
member’s valuemust be initialized to a
value different from null,otherwise a
scala.UnitializedError is thrown.

For every class type T such that T <: scala.AnyRef and not T <: scala.NotNull one has scala.Null <: T.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读