Skip to content

Instantly share code, notes, and snippets.

@mikehearn
Created December 14, 2015 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehearn/ad97d716d4fefac0f78e to your computer and use it in GitHub Desktop.
Save mikehearn/ad97d716d4fefac0f78e to your computer and use it in GitHub Desktop.
Rough sketch of possible linear types in kotlin (doesn't work with today's compiler)
open class LinearVal<T>(private val _v: T) {
open operator fun invoke(): T {
return _v
}
inline fun move(): LinearVal<T> {
if (this !is UnavailableLinearVal)
throw AssertionError()
@Suppress("DEPRECATION")
return __dupe()
}
@Deprecated(message = "Internal use only")
fun __dupe() = LinearVal(_v)
companion object {
fun <T> of(o: T): LinearVal<T> = UnavailableLinearVal<T>(o)
}
}
class UnavailableLinearVal<T> internal constructor(_v: T) : LinearVal<T>(_v) {
@Deprecated(message = "This value has been consumed", level = DeprecationLevel.ERROR)
override operator fun invoke(): T = throw AssertionError()
}
// USAGE
data class Person(val age: Int, val name: String)
fun main(args: Array<String>) {
val x = LinearVal.of(Person(31, "Mike"))
println("${x().name} is ${x().age}")
// If you manually inline this call by hand, x() yields an error below.
val y = x.move()
println("value now is ${x()}") // ERROR
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment