Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface Add<T> {
- operator fun <T1 : T> T1.plus(other: T1): T1
- }
- object IntAdd : Add<Int> {
- override fun <T1 : Int> T1.plus(other: T1): T1 {
- return (this + other) as T1 // This actually calls the member Int.plus
- }
- }
- object ListAdd : Add<List<Any?>> {
- override fun <T1 : List<Any?>> T1.plus(other: T1): T1 {
- return buildList(size + other.size) {
- addAll(this@plus)
- addAll(other)
- } as T1
- }
- }
- context(Add<R>)
- fun <T, R, R1: R> Iterable<T>.sumOf(selector: (T) -> R1): R1? {
- var sum: R1? = null
- for (element in this) {
- sum = if (sum == null) {
- selector(element)
- } else {
- sum + selector(element)
- }
- }
- return sum
- }
- context(Add<T>)
- fun <T, T1: T> Iterable<T1>.sum(): T1? {
- return sumOf { it }
- }
- fun test(){
- with(ListAdd){
- // Intellij shows that this is a List<String>?, success!!
- val bigList = listOf(listOf("hello"), listOf("world"), listOf("this", "actually", "works", "yo")).sum()
- println(bigList)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement