Created
December 12, 2019 14:30
-
-
Save bastman/103e1bfb6c708cda24eddacc8653f48d to your computer and use it in GitHub Desktop.
kotlin phantom types example - (generics, extensions)
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
// 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