Kotlin 中的字符串扩展

Extension to String in Kotlin

我创建了一个 class 并向其添加了一个与成员函数具有相同签名的扩展,并执行此方法它始终执行成员方法。

class Worker {
   fun work() = "...working"
}
fun Worker.work() = "...still working"

我为一个已经可用的方法 replace 创建了一个字符串 class 的扩展并执行这个 replace 方法;它改为调用扩展方法并给出 Hell 作为输出。

   fun String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String =  this.substring(0, this.length - 1);

然后

fun main(args: Array<String>) {
    val worker = Worker()
    println(worker.work()) // output: ...working

    val myString= "Hello"
    val result1 = myString.replace("Hello", "Bye")
    println("First character is: $result1") // output: First character is: Hell
}

我缺少什么?我原以为 replace 会给出 Bye 作为输出。

val myString= "Hello"
val result1 = myString.replace("Hello", "Bye")
println("First character is: $result1") // output: First character is: Bye

字符串如何在带有扩展的 Kotlin 中工作?

请注意,标准库中现有的 replace 函数也是扩展函数,在 kotlin.text 包中声明。

fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String

您可以访问它,因为 kotlin.text 是隐式导入的。

因为你的 replace 和现有的 replace 都是扩展函数,但是现有的 replace 是隐式导入的,重载解析选择你的 replace.

确切的优先级在 language specification:

中描述

If a call is correct, for a callable f with an explicit receiver e of type T the following sets are analyzed (in the given order):

  1. Non-extension member callables named f of type T;
  2. [...]
  3. [...]
  4. Extension callables named f, whose receiver type U conforms to type T, declared in the package scope;
  5. [...]
  6. Implicitly imported extension callables named f (either from the Kotlin standard library or platform-specific ones), whose receiver type U conforms to type T.

[...]

When analyzing these sets, the first set which contains any applicable callable is picked for c-level partition, which gives us the resulting overload candidate set.

集合 6 包含标准库中现有的 replace。第 4 组包含您声明的 replacework 扩展。集合 1 包含在 Worker.

中声明的 work 方法

由于 Kotlin 查找名称的顺序不同,您会看到不同的结果,具体取决于原始函数的声明位置和导入方式。