Skip to content

Instantly share code, notes, and snippets.

@sczerwinski
Created March 10, 2019 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sczerwinski/effb29461eb851cd8f8a9617989def1b to your computer and use it in GitHub Desktop.
Save sczerwinski/effb29461eb851cd8f8a9617989def1b to your computer and use it in GitHub Desktop.
Comparison of `!!` operator, `requireNotNull()`, `checkNotNull()` and null-safe operators: `?.`, `?:`
import org.junit.Test
class NotNullAssertionOperator {
@Test
@Throws(Exception::class)
fun exclamation() {
fun square(x: Double?): Double = x!!.times(x)
square(null)
}
@Test
@Throws(Exception::class)
fun require() {
fun square(x: Double?): Double = requireNotNull(x) { "Value is null" }.times(x)
square(null)
}
@Test
@Throws(Exception::class)
fun check() {
fun square(x: Double?): Double = checkNotNull(x) { "Value is null" }.times(x)
square(null)
}
@Test
@Throws(Exception::class)
fun safe() {
fun square(x: Double?): Double = x?.times(x) ?: 0.0
square(null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment