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:
James Strachan
2012-02-09 06:25:25 +00:00
parent 2dfb1fef0e
commit d604272744
2 changed files with 8 additions and 26 deletions
-11
View File
@@ -69,14 +69,3 @@ inline fun <T> Iterator<T>.toTreeSet() = to(TreeSet<T>())
Run function 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()
}
+8 -15
View File
@@ -6,6 +6,7 @@ import stdhack.test.*
class GetOrElseTest() : TestSupport() {
val v1: String? = "hello"
val v2: String? = null
var counter = 0
fun testDefaultValue() {
assertEquals("hello", v1?: "bar")
@@ -23,26 +24,18 @@ class GetOrElseTest() : TestSupport() {
}
}
/** TODO not supported yet?
fun testLazyDefaultValue() {
var counter = 0
assertEquals("hello", v1?: { counter++; "bar"})
assertEquals(counter, 0, "counter should not be incremented yet")
assertEquals("bar", v2?: { counter++; "bar"})
assertEquals(counter, 1, "counter should be incremented in the default function")
fun calculateBar(): String {
counter++
return "bar"
}
*/
fun testLazyDefaultValueUsingMethod() {
var counter = 0
fun testLazyDefaultValue() {
counter = 0
assertEquals("hello", v1.getOrElse{ counter++; "bar"})
assertEquals("hello", v1?: calculateBar())
assertEquals(counter, 0, "counter should not be incremented yet")
assertEquals("bar", v2.getOrElse{ counter++; "bar"})
assertEquals("bar", v2?: calculateBar())
assertEquals(counter, 1, "counter should be incremented in the default function")
}
}