Created
March 10, 2019 00:18
-
-
Save sczerwinski/effb29461eb851cd8f8a9617989def1b to your computer and use it in GitHub Desktop.
Comparison of `!!` operator, `requireNotNull()`, `checkNotNull()` and null-safe operators: `?.`, `?:`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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