Skip to content

Instantly share code, notes, and snippets.

@bastman
Created December 12, 2019 14:30
Show Gist options
  • Save bastman/103e1bfb6c708cda24eddacc8653f48d to your computer and use it in GitHub Desktop.
Save bastman/103e1bfb6c708cda24eddacc8653f48d to your computer and use it in GitHub Desktop.
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