Stworzyłem metody pomocnika buildChain
który zasadniczo tworzy łańcuch obiektów podanych że implementować interfejs IChain<T>
i ustawić umów next
członekprostsze lub bardziej funkcjonalny sposób łączenia obiektów w Kotlin
Kodeks
interface Chain<T> {
var next: T?
operator fun plus(next: T): T?
}
fun <T : Chain<T>> buildChain(first: T, vararg members: T): T {
var next: T? = null
members.forEachIndexed { i, t ->
if (i == 0) {
next = first + t
} else {
next = next?.run { this + t }
}
}
return first
}
przykładów realizacji
data class Person(val name: String) : Chain<Person> {
override var next: Person? = null
override fun plus(next: Person): Person? {
this.next = next
return next
}
}
fun createPersonChain()
= buildChain(Person("Bob"), Person("Bitzy"), Person("Blitzy"))
Przykâadowa implementaion
@JvmStatic fun main(args: Array<String>) {
var first = createPersonChain()
// first.name = "Bob"
// first.next.name = "Bitzy"
// first.next.next.name = "Blitzy"
}
Czy istnieje functional
lub simpler
sposób acheiving się code
powyżej utrzymując zużycie implementaion samo?
Dzięki skrótowi działa jak urok, zabawne jest to, że właśnie nauczyłem się funkcji składania w ciągu dnia i nie zdawałem sobie sprawy, że można go użyć w połączeniu z łańcuchem kodu –