Created
December 14, 2015 21:11
-
-
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)
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
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