Created
January 18, 2016 16:36
-
-
Save norswap/72b0f2d14442aeb444f5 to your computer and use it in GitHub Desktop.
Plugin Interface Proposal Example for Kotlin
This file contains hidden or 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
// Basic setup | |
interface Exp | |
data class Lit(val x: Int): Exp | |
data class Add(val x: Exp, val y: Exp): Exp | |
val exp0 = Add(Lit(42), Lit(0x52)) | |
// Adding a print operation | |
plugin interface Print { fun print(): String } | |
abstract instance Exp: Print | |
instance Lit: Print { | |
override fun print() = x.toString() | |
} | |
instance Add: Print { | |
override fun print() = "${x.print()} + ${y.print()}" | |
} | |
// Adding new data variants | |
data class Bool(val x: Boolean): Exp | |
data class Iff(val x: Exp, val y: Exp, val z: Exp): Exp | |
// Making the data variants printable | |
instance Bool: Print { | |
override fun print() = x.toString() | |
} | |
instance Iff: Print { | |
override fun print() = "if (${x.print()}) then ${y.print()} else ${z.print()}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment