zapped the redundant getOrElse method as the ?: does indeed work with lazy expressions (no function definition required) - thanks for spotting this Andrey! :)
This commit is contained in:
@@ -69,14 +69,3 @@ inline fun <T> Iterator<T>.toTreeSet() = to(TreeSet<T>())
|
|||||||
Run function f
|
Run function f
|
||||||
*/
|
*/
|
||||||
inline fun <T> run(f: () -> T) = f()
|
inline fun <T> run(f: () -> T) = f()
|
||||||
|
|
||||||
/*
|
|
||||||
Allow a default value to be lazily provided from a function when converting a nullable type to a non-nullable type
|
|
||||||
*/
|
|
||||||
// TODO would be nice to replace this with the ?: notation instead allowing a function as an argument for the default :)
|
|
||||||
inline fun <T> T?.getOrElse(defaultValueFactory: ()-> T): T {
|
|
||||||
return if (this != null)
|
|
||||||
this
|
|
||||||
else
|
|
||||||
defaultValueFactory()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import stdhack.test.*
|
|||||||
class GetOrElseTest() : TestSupport() {
|
class GetOrElseTest() : TestSupport() {
|
||||||
val v1: String? = "hello"
|
val v1: String? = "hello"
|
||||||
val v2: String? = null
|
val v2: String? = null
|
||||||
|
var counter = 0
|
||||||
|
|
||||||
fun testDefaultValue() {
|
fun testDefaultValue() {
|
||||||
assertEquals("hello", v1?: "bar")
|
assertEquals("hello", v1?: "bar")
|
||||||
@@ -23,26 +24,18 @@ class GetOrElseTest() : TestSupport() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** TODO not supported yet?
|
fun calculateBar(): String {
|
||||||
|
counter++
|
||||||
|
return "bar"
|
||||||
|
}
|
||||||
|
|
||||||
fun testLazyDefaultValue() {
|
fun testLazyDefaultValue() {
|
||||||
var counter = 0
|
counter = 0
|
||||||
|
|
||||||
assertEquals("hello", v1?: { counter++; "bar"})
|
assertEquals("hello", v1?: calculateBar())
|
||||||
assertEquals(counter, 0, "counter should not be incremented yet")
|
assertEquals(counter, 0, "counter should not be incremented yet")
|
||||||
|
|
||||||
assertEquals("bar", v2?: { counter++; "bar"})
|
assertEquals("bar", v2?: calculateBar())
|
||||||
assertEquals(counter, 1, "counter should be incremented in the default function")
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
fun testLazyDefaultValueUsingMethod() {
|
|
||||||
var counter = 0
|
|
||||||
|
|
||||||
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")
|
assertEquals(counter, 1, "counter should be incremented in the default function")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user