Kotlin申请String无法正常工作 [英] Kotlin apply on String not working as expected
问题描述
我正在尝试使用kotlin的所有功能,但似乎其中一些功能无法正常工作,或者可能是我的错.
I am trying to use all features of kotlin, but seems not of them are working, or may be it's my fault.
因此,从apply
到String
无效.示例:
So, apply
to String
not work. Example:
val str = someStr.apply {
toUpperCase()
if (contains("W")) replace("W", "w")
}
输入-> xywz
Input -> xywz
输出-> xywz
预期-> XYwZ
Java风格:
val str = it.text().toString().toUpperCase()
if (str.contains("W")) str.replace("W", "w")
输入-> xywz
Input -> xywz
输出-> XYwZ
预期-> XYwZ
我做错什么了吗?
推荐答案
toUpperCase()
返回字符串的副本(字符串是不可变的).因此,您需要将返回的值存储为apply()
中的独立(不是最后)语句,它会丢失.
toUpperCase()
returns a copy of the string (strings are immutable). So you need to store the returned value, as a stand-alone (not last) statement inside apply()
it is lost.
此外,如果返回表达式,则不能在没有else
的情况下使用if
.您甚至不需要contains()
.
Also, you can't use if
without else
, if you return an expression. The contains()
is not even needed in your case.
您可能想做的是直接调用toUpperCase()
和replace()
:
What you probably would like to do is call toUpperCase()
and replace()
directly:
val str = someStr.toUpperCase().replace("W", "w")
这篇关于Kotlin申请String无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!