I'm trying to learn functional programming in Kotlin and am having difficulty making this code work:
import java.util.*
fun caseName(br: String, c: Int): String {
if (c == 0) {
return br.toLowerCase()
} else {
return br.toUpperCase()
}
}
fun mapIt(ns: ArrayList<String>, f: (String, Int) -> String): List<String> {
val coll: List<String> = ns.map {it -> f(it, _)}
return coll
}
fun main(args: Array<String>) {
val names = arrayListOf("Joe", "Bill", "Murrary")
val cased = mapIt(names, (::caseName)(_, 0))
println(cased.first())
}
How do I get mapIt to recognize the case flag when mapping over the list?
Thank you!
EDIT: The case above is a simplified version of the following, which does not work either...
data class Borrower(val name: String, val maxBooks: Int) {
companion object {
fun getName(br: Borrower, c: Int): String {
if (c == 0) {
return br.name.toLowerCase()
} else {
return br.name.toUpperCase()
}
}
fun findBorrower(n: String, brs: ArrayList<Borrower>, f: (Borrower) -> String): Borrower? {
val coll: List<Borrower> = brs.filter { it -> f(it) == n }
if (coll.isEmpty()) {
return null
} else return coll.first()
}
}
}
fun main(args: Array<String>) {
val br1 = Borrower(name = "Borrower1", maxBooks = 1)
val br2 = Borrower(name = "Borrower2", maxBooks = 2)
val br3 = Borrower(name = "Borrower3", maxBooks = 3)
val br4 = Borrower(name = "borrower4", maxBooks = 4)
val br5 = Borrower(name = "BORROWER5", maxBooks = 5)
val brs1 = arrayListOf(br1, br2, br3, br4, br5)
val c = Borrower.findBorrower("borrower3", brs1, {Borrower.Companion::getName(it, 0)})
println(c)
}