Kotlin 应用于 String 未按预期工作
Kotlin apply on String not working as expected
我正在尝试使用 kotlin 的所有功能,但似乎没有一个能正常工作,或者可能是我的错。
因此,apply
到 String
不起作用。示例:
val str = someStr.apply {
toUpperCase()
if (contains("W")) replace("W", "w")
}
Input -> xywz
Output -> xywz
Expected -> XYwZ
Java 风格:
val str = it.text().toString().toUpperCase()
if (str.contains("W")) str.replace("W", "w")
Input -> xywz
Output -> XYwZ
Expected -> XYwZ
我是不是做错了什么?
toUpperCase()
returns 字符串的副本(字符串是不可变的)。因此,您需要存储 returned 值,作为 apply()
中的独立(不是最后一个)语句,它已丢失。
此外,如果您 return 表达式,则不能在没有 else
的情况下使用 if
。 contains()
在你的情况下甚至不需要。
您可能想要做的是直接调用 toUpperCase()
和 replace()
:
val str = someStr.toUpperCase().replace("W", "w")
实际上 apply
does not return the value you calculated. You may rather want to use either: run
, let
or with
。此外,可能更重要的是,您没有指定 else
路径。这可能 return 你 Unit
而不是一个值,所以你可能想要指定应该 return 否则。最后,这些方法中的调用不是链接的。首先调用 toUpperCase
不会改变任何东西......它几乎是死代码......所以你可能想写这样的东西:
val str = with(someStr) {
toUpperCase().run {
if (contains("W")) replace("W", "w")
else this
}
}
但是我只是使用 run/let/with 来演示它的用法,因为您已经使用过 apply...您显示的 Java 方法在这方面当然更容易,最简单的解决方案是由于 replace
默认情况下区分大小写,因此 TheOperator 显示的只是首先省略您的条件。
“应用”文档:
Calls the specified function block with this value as its receiver and
returns this value.
因此它 returns 原始值(“此值”)。
你应该用“let”代替:
val str = someStr.let {
it.toUpperCase().replace("W", "w")
}
但是你可以使用:
val str = someStr.toUpperCase().replace("W", "w")
我正在尝试使用 kotlin 的所有功能,但似乎没有一个能正常工作,或者可能是我的错。
因此,apply
到 String
不起作用。示例:
val str = someStr.apply {
toUpperCase()
if (contains("W")) replace("W", "w")
}
Input -> xywz
Output -> xywz
Expected -> XYwZ
Java 风格:
val str = it.text().toString().toUpperCase()
if (str.contains("W")) str.replace("W", "w")
Input -> xywz
Output -> XYwZ
Expected -> XYwZ
我是不是做错了什么?
toUpperCase()
returns 字符串的副本(字符串是不可变的)。因此,您需要存储 returned 值,作为 apply()
中的独立(不是最后一个)语句,它已丢失。
此外,如果您 return 表达式,则不能在没有 else
的情况下使用 if
。 contains()
在你的情况下甚至不需要。
您可能想要做的是直接调用 toUpperCase()
和 replace()
:
val str = someStr.toUpperCase().replace("W", "w")
实际上 apply
does not return the value you calculated. You may rather want to use either: run
, let
or with
。此外,可能更重要的是,您没有指定 else
路径。这可能 return 你 Unit
而不是一个值,所以你可能想要指定应该 return 否则。最后,这些方法中的调用不是链接的。首先调用 toUpperCase
不会改变任何东西......它几乎是死代码......所以你可能想写这样的东西:
val str = with(someStr) {
toUpperCase().run {
if (contains("W")) replace("W", "w")
else this
}
}
但是我只是使用 run/let/with 来演示它的用法,因为您已经使用过 apply...您显示的 Java 方法在这方面当然更容易,最简单的解决方案是由于 replace
默认情况下区分大小写,因此 TheOperator 显示的只是首先省略您的条件。
“应用”文档:
Calls the specified function block with this value as its receiver and returns this value.
因此它 returns 原始值(“此值”)。
你应该用“let”代替:
val str = someStr.let {
it.toUpperCase().replace("W", "w")
}
但是你可以使用:
val str = someStr.toUpperCase().replace("W", "w")