kotlin - Kotlin 将字符串映射到另一种类型?
问题描述
很快,我可以做到
"Some String".map { SomeObject($0) }
在 kotlin 中,字符串似乎被视为 char 数组,因此结果是每个字符的映射。是否有可能获得类似我发布的快速代码的行为?
"Some String".map { SomeObject(it) }
解决方案
You can accomplish something like that with let
:
"Some String".let { SomeObject(it) }
If you have an appropriate constructor in place (e.g. constructor(s : String) : this(...)
) you can also call it as follows:
"Some String".let(::SomeObject)
run
and with
work also, but are usually taken if you want to rather call a method of the receiver on it. Using run
/with
for this would look as follows:
"Some String".run { SomeObject(this) }
with ("Some String") { SomeObject(this) }
// but run / with is rather useful for things like the following (where the shown function calls are functions of SomeObject):
val x = someObject.run {
doSomethingBefore()
returningSomethingElse()
}