Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
kotlin phantom types example - (generics, extensions)
// phantom types
// https://proandroiddev.com/phantom-types-in-kotlin-afd3f59fde10
sealed class DoorState
object Open: DoorState()
object Closed: DoorState()
/*
class Door(val state: DoorState) {
fun open() = Door(Open).also { println("open()") }
fun close() = Door(Closed).also { println("close()") }
}
*/
class Door<out T: DoorState>(val state: T)
fun Door<Closed>.open() = Door(Open).also { println("open()") }
fun Door<Open>.close() = Door(Closed).also { println("close()") }
fun main() {
Door(Closed)
.also { println("=========") }
.also { println("state: ${it.state}") }
.open()
.also { println("state: ${it.state}") }
Door(Open)
.also { println("=========") }
.also { println("state: ${it.state}") }
.close()
.also { println("state: ${it.state}") }
// will no longer compile :) ...
/*
Door(Open)
.also { println("=========") }
.also { println("state: ${it.state}") }
.open()
.also { println("state: ${it.state}") }
Door(Closed)
.also { println("=========") }
.also { println("state: ${it.state}") }
.close()
.also { println("state: ${it.state}") }
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment