added a helper method for easily converting from a nullable type to a non nullable type with a non-lazy value, or lazy factory function
This commit is contained in:
@@ -68,4 +68,24 @@ inline fun <T> Iterator<T>.toTreeSet() = to(TreeSet<T>())
|
||||
/*
|
||||
Run function f
|
||||
*/
|
||||
inline fun <T> run(f: () -> T) = f()
|
||||
inline fun <T> run(f: () -> T) = f()
|
||||
|
||||
/*
|
||||
Allow a default value to be provided when converting a nullable type to a non-nullable type
|
||||
*/
|
||||
inline fun <T> T?.getOrElse(defaultValue: T): T {
|
||||
return if (this != null)
|
||||
this
|
||||
else
|
||||
defaultValue
|
||||
}
|
||||
|
||||
/*
|
||||
Allow a default value to be lazily provided from a function when converting a nullable type to a non-nullable type
|
||||
*/
|
||||
inline fun <T> T?.getOrElse(defaultValueFactory: ()-> T): T {
|
||||
return if (this != null)
|
||||
this
|
||||
else
|
||||
defaultValueFactory()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package test.standard
|
||||
|
||||
import std.*
|
||||
import stdhack.test.*
|
||||
import stdhack.test.assertEquals
|
||||
|
||||
class GetOrElseTest() : TestSupport() {
|
||||
val v1: String? = "hello"
|
||||
val v2: String? = null
|
||||
|
||||
fun testDefaultValue() {
|
||||
/**
|
||||
TODO compiler error?
|
||||
|
||||
assertEquals("hello", v1.getOrElse("bar"))
|
||||
assertEquals("bar", v2.getOrElse("bar"))
|
||||
|
||||
expect("hello") {
|
||||
v1.getOrElse("bar")
|
||||
}
|
||||
expect("bar") {
|
||||
v2.getOrElse("bar")
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
fun testLazyDefaultValue() {
|
||||
var counter = 0
|
||||
|
||||
/**
|
||||
TODO compiler error?
|
||||
assertEquals("hello", v1.getOrElse{ counter++; "bar"}
|
||||
assertEquals(counter, 0, "counter should not be incremented yet")
|
||||
|
||||
assertEquals("bar", v2.getOrElse{ counter++; "bar"}
|
||||
assertEquals(counter, 1, "counter should be incremented in the default function")
|
||||
*/
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user