kotlin - 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(" ")
被调用两次。
如何以更聪明的方式编写函数式编程风格?
fold
PS 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
}
解决方案
这有点简单。我看不到一种使用方法,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] }
}
推荐阅读
- telnetlib - 我有 telnetlib python 的问题
- python - 打印 Vaex HDF5 数据时显示完整整数而不是科学计数法
- javascript - 用于反应的 nginx 路径路由
- r - 如何将R中的函数与未知的上限或下限集成
- c# - 根据表单大小更改锚属性
- python - 熊猫箱内的零填充
- swift - xcode 10.1 中的演示风格
- snowflake-cloud-data-platform - 雪花中列注释的最大长度
- powershell - Powershell选择并删除文件夹中的最后一个创建项目
- php - 我正在尝试使用 codeigniter 从数据库中获取年份以显示到网页上