Last active
February 15, 2018 17:27
-
-
Save pakoito/f4a67de7fff57710d2aa41afd676bc07 to your computer and use it in GitHub Desktop.
Recursive datatypes in Kotlin
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
sealed class NaturalNum | |
object Zero: NaturalNum() | |
class PlusOne<N: NaturalNum>(): NaturalNum() | |
fun num(zero: Zero) = 0 | |
fun num(one: PlusOne<Zero>) = 1 | |
@JvmName("two") | |
fun num(two: PlusOne<PlusOne<Zero>>) = 2 | |
fun main(args: Array<String>) { | |
val a: PlusOne<Zero> = PlusOne() | |
val b: PlusOne<PlusOne<Zero>> = PlusOne() | |
println(num(Zero)) // 0 | |
println(num(a)) // 1 | |
println(num(b)) // 2 | |
val c: PlusOne<PlusOne<PlusOne<Zero>>> = PlusOne() | |
// println(num(c)) **compilation error** | |
// fun <N: NaturalNum> thing(a: PlusOne<N>) = num(a) **compilation error** | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The functionality is limited to cases where the generics are known during compilation, see line 26.