Advertisement
kyay10

Hacky List Add implementation using context receivers

May 28th, 2022
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.08 KB | None | 0 0
  1. interface Add<T> {
  2.     operator fun <T1 : T> T1.plus(other: T1): T1
  3. }
  4.  
  5. object IntAdd : Add<Int> {
  6.     override fun <T1 : Int> T1.plus(other: T1): T1 {
  7.         return (this + other) as T1 // This actually calls the member Int.plus
  8.     }
  9. }
  10.  
  11. object ListAdd : Add<List<Any?>> {
  12.     override fun <T1 : List<Any?>> T1.plus(other: T1): T1 {
  13.         return buildList(size + other.size) {
  14.             addAll(this@plus)
  15.             addAll(other)
  16.         } as T1
  17.     }
  18. }
  19.  
  20. context(Add<R>)
  21. fun <T, R, R1: R> Iterable<T>.sumOf(selector: (T) -> R1): R1? {
  22.     var sum: R1? = null
  23.     for (element in this) {
  24.         sum = if (sum == null) {
  25.             selector(element)
  26.         } else {
  27.             sum + selector(element)
  28.         }
  29.     }
  30.     return sum
  31. }
  32. context(Add<T>)
  33. fun <T, T1: T> Iterable<T1>.sum(): T1? {
  34.     return sumOf { it }
  35. }
  36. fun test(){
  37.     with(ListAdd){
  38.         // Intellij shows that this is a List<String>?, success!!
  39.         val bigList = listOf(listOf("hello"), listOf("world"), listOf("this", "actually", "works", "yo")).sum()
  40.         println(bigList)
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement