Skip to content

Commit

Permalink
Extensions to destructure nullable tuples to nullable local variables
Browse files Browse the repository at this point in the history
  • Loading branch information
npryce committed Apr 8, 2024
1 parent 2a47f0c commit 9421ed2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
16 changes: 16 additions & 0 deletions tuples4k/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,21 @@ task generateAsNullableFunctions {
}
}

task generateNullableDestructuringExtensions {
dependsOn "recreateGeneratedSrcDir"

doLast {
generateSourceFile("nullable-destructuring.kt") { out ->
for (n in 2..maxTupleSize) {
for (i in 1..n) {
out.println("operator fun <${params(n, "T")}> ${tupleType(n)}?.component$i(): T$i? = this?.component$i()")
}
out.println()
}
}
}
}


task generateContainsFunctions {
dependsOn "recreateGeneratedSrcDir"
Expand All @@ -216,6 +231,7 @@ task generateSrcMain {
dependsOn "generatePlusFunctions"
dependsOn "generateNonNullFunctions"
dependsOn "generateAsNullableFunctions"
dependsOn "generateNullableDestructuringExtensions"
dependsOn "generateContainsFunctions"
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package dev.forkhandles.tuples
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test

class TupleExampleTest {
Expand Down Expand Up @@ -48,7 +49,7 @@ class TupleExampleTest {
}

@Test
fun `contains`() {
fun contains() {
assertTrue(0 !in tuple(1,2,3))
assertTrue(1 in tuple(1,2,3))
assertTrue(2 in tuple(1,2,3))
Expand All @@ -58,4 +59,18 @@ class TupleExampleTest {
assertTrue("x" in tuple("x","y"))
assertTrue("z" !in tuple("x","y"))
}

@Test
fun `destructuring nullable tuple`() {
@Suppress("RedundantNullableReturnType")
val a : Tuple2<String,Int>? = tuple("A", 1)
val (a1,a2) = a
assertEquals("A", a1)
assertEquals(1, a2)

val b : Tuple2<String,Int>? = null
val (b1,b2) = b
assertNull(b1)
assertNull(b2)
}
}

0 comments on commit 9421ed2

Please sign in to comment.