Created
February 11, 2019 18:53
-
-
Save raxityo/9d0ded596cb38845987ea598e17908f5 to your computer and use it in GitHub Desktop.
Sample class to demonstrate usage of `tryOptional` in Kotlin. See: https://gist.github.com/raxityo/8a109787966abc38c27b5620ce93b225
This file contains 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
class TokenGenerator { | |
private var canObtainToken = true | |
private var token = "TOKEN" | |
fun obtainToken(): String { | |
if (!canObtainToken) { | |
throw Error() | |
} | |
canObtainToken = false | |
return token | |
} | |
fun returnToken() { | |
canObtainToken = true | |
} | |
} | |
val tokenGenerator = TokenGenerator() | |
println(tokenGenerator.obtainToken()) // Prints: TOKEN | |
val anotherToken = tryOptional { tokenGenerator.obtainToken() } | |
println(anotherToken) // Prints: null | |
// Optional chaining. | |
// Prints: NULL TOKEN | |
tryOptional { | |
tokenGenerator.obtainToken() | |
}?.let { | |
println(it) | |
} ?: println("null TOKEN") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment