Hi!
Playing with M4 and it seems very solid.
I noticed there isn’t any copy methods for collection classes, isn’t that something that should be useful to have?
Also, maybe the method name should be changed from copy() to change()?
Take a look at this code and say what you think:
import java.util.ArrayList
data class Person(val firstName: String, val lastName: String)
fun Person.asMarried(newLastName: String) = this.copy(lastName = newLastName)
fun Person.asSmurf() = this.copy(lastName = “Smurf”)
fun main(args: Array<String>) {
val persons = listOf(
Person(“Tom”, “Jones”),
Person(“David”, “Bowie”),
Person(“David”, “Hasselhoff”),
Person(“James”, “Brown”))
val persons1 = persons.copy(1…2, { it.copy(lastName = “Smurf”) })
val persons2 = persons1.copy(1…2, { it.asSmurf() })
val persons3 = persons1.copy(1, { it.asSmurf() })
println(persons1)
println(persons2)
println(persons3)
}
fun <A> List<A>.copy(f: (A) -> A): List<A> = this.map { f(it) }
fun <A> List<A>.copy(index: Int, f: (A) -> A): List<A> = this.copy(index…index, f)
fun <A> List<A>.copy(range: IntRange, f: (A) -> A): List<A> {
return this.indexedMap {(i, v) ->
if (i in range) f(v) else v
}
}
fun <A, B> Iterable<A>.indexedMap(f: (Int, A) -> B): List<B> {
val answer = ArrayList<B>()
var nextIndex = 0
for (e in this) {
answer.add(f(nextIndex, e))
nextIndex++
}
return answer
}
Output would be:
[Person(firstName=Tom, lastName=Jones), Person(firstName=David, lastName=Smurf), Person(firstName=David, lastName=Smurf), Person(firstName=James, lastName=Brown)]
[Person(firstName=Tom, lastName=Jones), Person(firstName=David, lastName=Smurf), Person(firstName=David, lastName=Smurf), Person(firstName=James, lastName=Brown)]
[Person(firstName=Tom, lastName=Jones), Person(firstName=David, lastName=Smurf), Person(firstName=David, lastName=Smurf), Person(firstName=James, lastName=Brown)]