使用map函数转换列表中的项目
Kotlin 1.4.21
我有一个产品列表,我想将价格转换为格式化的字符串。但是,价格不会更改为格式化的价格。
IE
orginal price: 1658
expected: "1,658.00"
actual: 1658
这是类结构
data class Product(
val productName: String,
val price: Double)
在这里,我正在使用我的项目列表,我想改变价格。
listOfProjects.map {
it.price.toAmount(2) // extension function that formats to 2 decimal places and converts to a string
}
if (listOfProjects.isNotEmpty()) {
// Do something with the list. However, the price hasn't changed
}
回答
您可能希望它执行in-place格式化。也许如果您分配一个输出变量,您将能够获得它:
val result = listOfProjects.map { it.price.toAmount(2) }
println(result)
或者,如果您val formattedPrice: String在Project类上添加一个属性,您可以像这样定义它:
val formattedPrice: String = price.toAmount(2)
然后你可以在一个toString()方法中使用这个属性。