Skip to content

Commit

Permalink
✨ Add Zero.Companion.orNull(Float) method (#719)
Browse files Browse the repository at this point in the history
  • Loading branch information
LVMVRQUXL committed Jan 9, 2025
1 parent 2c5dc6b commit e564913
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions subprojects/library/src/api/types.api
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ public final class org/kotools/types/Zero {

public final class org/kotools/types/Zero$Companion {
public final synthetic fun orNull (B)Lorg/kotools/types/Zero;
public final synthetic fun orNull (F)Lorg/kotools/types/Zero;
public final synthetic fun orNull (I)Lorg/kotools/types/Zero;
public final synthetic fun orNull (J)Lorg/kotools/types/Zero;
public final synthetic fun orNull (S)Lorg/kotools/types/Zero;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,36 @@ public class Zero {
null
}

/**
* Creates an instance of [Zero] from the specified [number], or returns
* `null` if the [number] is other than zero.
*
* <br>
* <details>
* <summary>
* <b>Calling from Kotlin</b>
* </summary>
*
* Here's an example of calling this method from Kotlin code:
*
* SAMPLE: [org.kotools.types.ZeroCompanionCommonSample.orNullWithFloat]
* </details>
* <br>
*
* This method is not available from Java code due to its non-explicit
* [support for nullable types](https://kotlinlang.org/docs/java-to-kotlin-nullability-guide.html#support-for-nullable-types).
*
* See the [orThrow] method for throwing an exception instead of
* returning `null` in case of invalid [number].
*/
@ExperimentalSince(KotoolsTypesVersion.V5_0_0)
@JvmSynthetic
public fun orNull(number: Float): Zero? = try {
this.orThrow(number)
} catch (exception: IllegalArgumentException) {
null
}

/**
* Creates an instance of [Zero] from the specified [number], or throws
* an [IllegalArgumentException] if the [number] is other than zero.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ class ZeroCompanionCommonSample {
assertNotNull(zero)
}

@Test
fun orNullWithFloat() {
val zero: Zero? = Zero.orNull(0f)
assertNotNull(zero)
}

@Test
fun orThrowWithByte() {
val number: Byte = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ class ZeroCompanionTest {
assertNull(actual)
}

@Test
fun orNullShouldFailWithFloatOtherThanZero() {
val number: Float = Float.randomNonZero()
val actual: Zero? = Zero.orNull(number)
assertNull(actual)
}

@Test
fun orThrowShouldFailWithByteOtherThanZero() {
val number: Byte = setOf(Byte.MIN_VALUE..-1, 1..Byte.MAX_VALUE)
Expand Down

0 comments on commit e564913

Please sign in to comment.