【发布时间】:2022-12-03 01:11:41
【问题描述】:
我正在尝试使用具有可选参数的自定义 toString 覆盖数据类的 toString 函数,但它没有按预期工作:
data class LatLong(
val latitude: Double,
val longitude: Double
){
// Override keyword not allowed by compiler here
fun toString(decimals: Int = 5) =
"${"%.${decimals}f".format(latitude)}, ${"%.${decimals}f".format(longitude)}"
}
fun main() {
println(LatLong(-123.0, 49.0)) // prints: "LatLong(latitude=-123.0, longitude=49.0)" i.e. does not call custom toString
println(LatLong(-123.0, 49.0).toString()) // prints: "LatLong(latitude=-123.0, longitude=49.0)" i.e. does not call custom toString
println(LatLong(-123.0, 49.0).toString(decimals=5)) // prints: "-123.00000, 49.00000"
}
问题是如何应该我重写它以获得您期望的行为(即上面的所有 3 个调用都应该使用自定义方法)?
我显然可以添加
override fun toString() = toString(decimals=5)
但这意味着定义默认参数两次,这是未来错误的一个秘诀。当然,我可以将默认值定义为常量和来自 toStringa 的引用,但它看起来很乱。令人惊讶的是LatLong(...).toString() 没有调用新方法。
处理这个问题的“Kotlinic”方法是什么?
【问题讨论】:
标签: kotlin inheritance overriding