Last active
September 14, 2018 23:05
-
-
Save ZacSweers/463500043b1a9708ba4e26c7ad1862fd to your computer and use it in GitHub Desktop.
Demo of how the Nothing type in Kotlin can allow a Swift-style guard function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.truth.Truth.assertThat | |
import org.junit.Test | |
inline fun <T> guard(receiver: T?, block: () -> Nothing): T { | |
if (receiver == null) { | |
block() | |
} | |
return receiver | |
} | |
class GuardTest { | |
fun example() { | |
val myTaco: String? = "taco" | |
val myGuardedTaco = guard(myTaco) { return } | |
// The following bit won't compile because the passed function doesn't return or throw an exception! | |
// val myUnguardedTaco = guard(myTaco) { | |
// // Not legal because I haven't returned or thrown an exception! | |
// } | |
} | |
fun returnTypeExample(): String { | |
val myTaco: String? = "taco" | |
return guard(myTaco) { return "No taco :(" } | |
} | |
@Test | |
fun test() { | |
val foo = "foo" | |
val bar = guard(foo) { | |
throw AssertionError("Should never reach here because foo is not null") | |
} | |
assertThat(bar).isEqualTo("foo") | |
} | |
@Test | |
fun testNull() { | |
val foo: String? = null | |
val bar = guard(foo) { return } | |
throw AssertionError("Should never reach here because foo is null") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment