diff --git a/CHANGELOG.md b/CHANGELOG.md index cbd54736..e49333b9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Added +- `T?.ifNotNull(block: () -> Unit): T?` +- `T?.ifNull(block: () -> Unit): T?` - `Graph` data structure ### Changed diff --git a/kotlin-stdlib/common/main/kotlin/com/javiersc/kotlin/stdlib/T.kt b/kotlin-stdlib/common/main/kotlin/com/javiersc/kotlin/stdlib/T.kt new file mode 100644 index 00000000..1e495550 --- /dev/null +++ b/kotlin-stdlib/common/main/kotlin/com/javiersc/kotlin/stdlib/T.kt @@ -0,0 +1,11 @@ +package com.javiersc.kotlin.stdlib + +public inline fun T?.ifNotNull(block: () -> Unit): T? { + if (this != null) block() + return this +} + +public inline fun T?.ifNull(block: () -> Unit): T? { + if (this == null) block() + return this +} diff --git a/kotlin-stdlib/common/test/kotlin/com/javiersc/kotlin/stdlib/TTest.kt b/kotlin-stdlib/common/test/kotlin/com/javiersc/kotlin/stdlib/TTest.kt new file mode 100644 index 00000000..c244ac89 --- /dev/null +++ b/kotlin-stdlib/common/test/kotlin/com/javiersc/kotlin/stdlib/TTest.kt @@ -0,0 +1,50 @@ +package com.javiersc.kotlin.stdlib + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +@Suppress("RedundantNullableReturnType") +class TTest { + + private val a: String? = "a" + private val b: String? = null + private val one: Int? = 1 + private val two: Int? = null + + @Test + fun ifNotNull() { + var isA = false + var isB = false + var isOne = false + var isTwo = false + + a.ifNotNull { isA = true } + b.ifNotNull { isB = true } + one.ifNotNull { isOne = true } + two.ifNotNull { isTwo = true } + + assertTrue { isA } + assertFalse { isB } + assertTrue { isOne } + assertFalse { isTwo } + } + + @Test + fun ifNull() { + var isA = false + var isB = false + var isOne = false + var isTwo = false + + a.ifNull { isA = true } + b.ifNull { isB = true } + one.ifNull { isOne = true } + two.ifNull { isTwo = true } + + assertFalse { isA } + assertTrue { isB } + assertFalse { isOne } + assertTrue { isTwo } + } +}