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:
James Strachan
2012-02-06 16:48:44 +00:00
parent 5f8a71eb21
commit 5057bf732e
2 changed files with 60 additions and 1 deletions
+21 -1
View File
@@ -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()
}
+39
View File
@@ -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")
*/
}
}