Created
September 4, 2016 16:18
-
-
Save debop/5dc9fa0eb9da015ccb5932b514038623 to your computer and use it in GitHub Desktop.
Product in Kotlin ported from Scala
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
interface Product { | |
val productArity: Int | |
fun elements(index: Int): Any? | |
fun toList(): List<*> = productIterator().toList() | |
fun productIterator(): Iterator<*> = object : Iterator<Any?> { | |
var currIndex = 0 | |
override fun hasNext(): Boolean = currIndex < productArity | |
override fun next(): Any? = elements(currIndex++) | |
} | |
fun productPrefix(): String = "" | |
} | |
interface Product1<out T1 : Any> : Product { | |
override val productArity: Int | |
get() = 1 | |
override fun elements(index: Int): Any = when (index) { | |
0 -> first | |
else -> throw IndexOutOfBoundsException(index.toString()) | |
} | |
val first: T1 | |
} | |
interface Product2<out A : Any, out B : Any> : Product { | |
override val productArity: Int | |
get() = 3 | |
override fun elements(index: Int): Any = when (index) { | |
0 -> first | |
1 -> second | |
else -> throw IndexOutOfBoundsException(index.toString()) | |
} | |
val first: A | |
val second: B | |
} | |
interface Product3<out A : Any, out B : Any, out C : Any> : Product { | |
override val productArity: Int | |
get() = 3 | |
override fun elements(index: Int): Any = when (index) { | |
0 -> first | |
1 -> second | |
2 -> third | |
else -> throw IndexOutOfBoundsException(index.toString()) | |
} | |
val first: A | |
val second: B | |
val third: C | |
} | |
interface Product4<out A : Any, out B : Any, out C : Any, out D : Any> : Product { | |
override val productArity: Int | |
get() = 3 | |
override fun elements(index: Int): Any = when (index) { | |
0 -> first | |
1 -> second | |
2 -> third | |
3 -> fourth | |
else -> throw IndexOutOfBoundsException(index.toString()) | |
} | |
val first: A | |
val second: B | |
val third: C | |
val fourth: D | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment