The ? operator usually works with Java libraries that may produce null.
import com.thoughtworks.dsl.keywords.NullSafe._
val myMap = new java.util.HashMap[String, String]();
((myMap.get("key1").? + myMap.get("key2").?): @ ?) should be(null)
,
You can use ? annotation to represent a nullable value.
import com.thoughtworks.dsl.keywords.NullSafe._
caseclass Tree(left: Tree @ ? = null, right: Tree @ ? = null, value: String @ ? = null)
val root: Tree @ ? = Tree(
left = Tree(
left = Tree(value = "left-left"),
right = Tree(value = "left-right")
),
right = Tree(value = "right")
)
A normal . is not null safe, when selecting left, right or value on a null value.
a[NullPointerException] should be thrownBy {
root.right.left.right.value
}
The above code throws an exception because root.right.left is null.
The exception can be avoided by using ? on a nullable value:
root.?.right.?.left.?.right.?.value should be(null)
The entire expression will be null if one of ? is performed on a null value.
The boundary of a null safe operator ? is the nearest enclosing expression
whose type is annotated as @ ?.
("Hello " + ("world " + root.?.right.?.left.?.value)) should be("Hello world null")
("Hello " + (("world " + root.?.right.?.left.?.value.?): @ ?)) should be("Hello null")
(("Hello " + ("world " + root.?.right.?.left.?.value.?)): @ ?) should be(null)
Note
The ? operator is only available on nullable values.
A type is considered as nullable if it is a reference type,
no matter it is annotated as @ ? or not.
import com.thoughtworks.dsl.keywords.NullSafe._
val explicitNullable: String @ ? = null
((explicitNullable.? + " Doe") : @ ?) should be(null)
val implicitNullable: String = null
((implicitNullable.? + " Doe") : @ ?) should be(null)
A type is considered as not nullable if it is a value type.
val implicitNotNullable: Int = 0"(implicitNotNullable.? + 42) : @ ?" shouldNot compile
Alternatively, a type can be considered as not nullable
by explicitly converting it to NotNull.
NullSafe is a keyword to perform
null
check.Author:
杨博 (Yang Bo)
The ? operator usually works with Java libraries that may produce
null
.You can use ? annotation to represent a nullable value.
A normal
.
is not null safe, when selectingleft
,right
orvalue
on anull
value.The above code throws an exception because
root.right.left
isnull
. The exception can be avoided by using ? on a nullable value:root.?.right.?.left.?.right.?.value should be(null)
The entire expression will be
null
if one of ? is performed on anull
value.The boundary of a null safe operator ? is the nearest enclosing expression whose type is annotated as
@ ?
.The ? operator is only available on nullable values. A type is considered as nullable if it is a reference type, no matter it is annotated as
@ ?
or not.A type is considered as not nullable if it is a value type.
Alternatively, a type can be considered as not nullable by explicitly converting it to NotNull.
NoneSafe for similar checks on scala.Options.