Kotlin map()重用相同的值

问题描述 投票:0回答:2

我有以下方法

    val dateFormat = SimpleDateFormat("yyyy-MM-dd")
    fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")
        return lines.map { l -> Pair(dateFormat.parse(l.split(" ")[0]), l.split(" ")[1]) }
    }

其中l.split(" ")被调用两次。

如何以函数式编程风格编写更聪明的方法?

PS 1:如果有可能,我对fold的解决方案感到好奇

PS 2:为了便于阅读,原始版本写为

 fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> {
        val lines = paragraph.split("\n")

        var results = mutableListOf<Pair<Date, String>>()
        for (line in lines) {
            val content = line.split(" ")
            val date: Date = dateFormat.parse(content[0])
            val firstName = content[1]
            results.add(Pair(date,firstName))
        }
        return results
    }
kotlin functional-programming
2个回答
2
投票
这有点简单。我看不到没有使它更复杂的使用fold的方法。

val dateFormat = SimpleDateFormat("yyyy-MM-dd") fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> = paragraph.split("\n") .map { with(it.split(" ")) { dateFormat.parse(this[0]) to this[1] } }


0
投票
我相信有更多实用且优化的方式来编写此代码,但这是一个带有示例的基本折叠+:

fun parseBirthdateLines(paragraph: String): List<Pair<Date, String>> { val lines = paragraph.split("\n") return lines.fold(listOf<Pair<Date, String>>()) { list, second -> with (second.split(" ")) { list + Pair(dateFormat.parse(this[0]), this[1]) } } }

© www.soinside.com 2019 - 2024. All rights reserved.