首页 > 解决方案 > Kotlin map() 重用相同的值

问题描述

我有以下方法

    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]) }
    }

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

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

foldPS 1:如果可能的话,我很好奇解决方案

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
    }

标签: kotlinfunctional-programming

解决方案


这有点简单。我看不到一种使用方法,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] }
        }

推荐阅读