Skip to content

Commit

Permalink
Add ifNotNull and ifNull functions
Browse files Browse the repository at this point in the history
  • Loading branch information
JavierSegoviaCordoba committed Oct 4, 2023
1 parent 0b6d152 commit e0a27c2
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Added

- `T?.ifNotNull(block: () -> Unit): T?`
- `T?.ifNull(block: () -> Unit): T?`
- `Graph` data structure

### Changed
Expand Down
11 changes: 11 additions & 0 deletions kotlin-stdlib/common/main/kotlin/com/javiersc/kotlin/stdlib/T.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.javiersc.kotlin.stdlib

public inline fun <T> T?.ifNotNull(block: () -> Unit): T? {
if (this != null) block()
return this
}

public inline fun <T> T?.ifNull(block: () -> Unit): T? {
if (this == null) block()
return this
}
Original file line number Diff line number Diff line change
@@ -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 }
}
}

0 comments on commit e0a27c2

Please sign in to comment.