【问题标题】:Kotlin: Why does override with additional optional arguments not work?Kotlin:为什么用额外的可选参数覆盖不起作用?
【发布时间】: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


    【解决方案1】:

    您不需要两次声明默认值。只需在toString覆盖中声明它,而不是在您自己的toString的参数列表中:

    override fun toString() = toString(decimals = 5)
    
    // make this a required parameter
    fun toString(decimals: Int) =
        "${"%.${decimals}f".format(latitude)}, ${"%.${decimals}f".format(longitude)}"
    

    当然,如果您有更多格式选项,这会变得有点复杂,但您始终可以将所有内容包装在一个(数据)类中,并以单个参数结束。

    data class FormatOptions(
        val decimals: Int = 5,
        val someOtherOption: Int = 10
    )
    
    override fun toString() = toString(FormatOptions(/* ... */))
    
    fun toString(options: FormatOptions): String = TODO()
    

    顺便说一下调用toString()的参数列表确切地匹配数据类自动声明的无参数toString重载。另一方面,如果它考虑可选参数,它只会匹配您声明的那个。因此,编译器有充分的理由更愿意将 LatLong(...).toString() 解析为无参数的 toString 方法,而不是您声明的方法。

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 1970-01-01
      • 2010-09-23
      • 2018-07-06
      • 2019-12-07
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多