代码之家  ›  专栏  ›  技术社区  ›  Psest328

Kotlin扩展函数-重写现有方法

  •  0
  • Psest328  · 技术社区  · 8 年前

    /**
     * Converts all of the characters in the string to upper case.
     *
     * @param str the string to be converted to uppercase
     * @return the string converted to uppercase or empty string if the input was null
     */
    fun String?.toUpperCase(): String = this?.toUpperCase() ?: ""
    
    • 这会怎么样?它会使 toUpperCase 零保险箱。
    • 我有什么问题?返回值, this?.toUpperCase() , 表示扩展函数

    是唯一的选择重命名我的扩展函数,还是有一种方法从其中引用“super”函数?

    1 回复  |  直到 8 年前
        1
  •  10
  •   pau1adam    8 年前

    不能重写现有成员函数。

    如果一个类有一个成员函数,并且定义了一个扩展函数 争论,成员总是获胜。

    source

    是唯一的选择重命名我的扩展函数,还是有一种方法从其中引用“super”函数?

    您必须重命名扩展函数,并从中调用要使用的成员函数。

        2
  •  4
  •   Fox Sleigh    7 年前

    这个 source 作为 pau1adam toUpperCase() 对于可为null的类型 String? 完全有效。

    • 打电话时 toUppercase() String ,则调用成员函数。
    • 打电话时 toUppercase() 在一个可以为null的 串? ,没有成员函数。这样就调用了扩展函数。

    安全呼叫接线员 ?. this 非空的 字符串 类型,这样您定义的函数就完全符合您的要求。

    您可以在 来源 ,他们解释了 Any?.toString() 可以实现。