Staff Engineer @ GrubHub
CKUG Co-Organizer
@wakingrufus
@wakingrufus@bigshoulders.city
wakingrufus
interface LoggingContext {
val log: Logger // This context provides a reference to a logger
}
context(LoggingContext)
fun startBusinessOperation() {
// You can access the log property
log.info("Operation has started")
}
fun test(loggingContext: LoggingContext) {
with(loggingContext) {
// You need to have LoggingContext in a scope
// to call startBusinessOperation()
startBusinessOperation()
}
}
fun <T> elvisLike(x: T, y: T): T = x ?: y
fun test(){
elvisLike("", null) // valid
}
fun <T : Any> elvisLike(x: T, y: T): T = x ?: y
fun test(){
val s : String? = null
elvisLike(s, "") // compile error at s
}
fun <T> elvisLike(x: T, y: T & Any): T & Any = x ?: y
fun test(){
val s : String? = null
elvisLike(s, null) // compile error on null
}
sealed class ReadResult {
data class Number(val value: Int) : ReadResult()
data class Text(val value: String) : ReadResult()
data object EndOfFile : ReadResult()
}
fun main() {
println(ReadResult.Number(1)) // Number(value=1)
println(ReadResult.Text("Foo")) // Text(value=Foo)
println(ReadResult.EndOfFile) // EndOfFile
}
@JvmInline
value class UserId<T>(val value: T)
fun printId(s: UserId<String>) {
println(s.value)
}
fun printId(s: UserId<UUID>) {
println(s.value.toString())
}
fun test(){
printId(UserId(""))
printId(UserId(UUID.randomUUID()))
}
@wakingrufus
@wakingrufus@mastodon.technology