Skip to content

Instantly share code, notes, and snippets.

@ZacSweers
Last active September 14, 2018 23:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZacSweers/463500043b1a9708ba4e26c7ad1862fd to your computer and use it in GitHub Desktop.
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
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