Kotlin 为 String 类型重载“-”

问题描述 投票:0回答:1

我最近一直在尝试 Kotlin。我现在有一项任务被困住了。 我需要重载字符串类型的运算符“-”。新函数应该从现有字符串中创建一个新字符串,“-”后不带字母。

像这样: “Hello World” - 'l' --> “Heo Word”

这是我进一步培训的一部分。不幸的是,文档中对此的解释非常糟糕,而且我班上的大多数人也无法处理它。老师只是说:“你自己找出来。”

不幸的是,由于我们只上了两堂课,所以我不知道如何应对。

string kotlin overloading minus
1个回答
0
投票

要在字符串上重载

-
运算符,我们需要创建一个扩展函数:

operator fun String.minus(other: String): String

然后,我们需要实际替换字符串。 kotlin stdlib 已经有一个函数可以为我们做到这一点:

fun String.replace(oldValue: String, newValue: String,  ignoreCase: Boolean = false): String

将这两个放在一起,我们得到这个函数:

operator fun String.minus(other: String) = this.replace(other, "")

我们为字符串定义

-
运算符的重载,然后在接收器上调用
replace
方法。

在这里尝试一下

operator fun String.minus(other: String) = this.replace(other, "") fun main() { println("Hello World" - "l") // Heo Word }
    
© www.soinside.com 2019 - 2024. All rights reserved.