在快速,我能做到
"Some String".map { SomeObject($0) }
Run Code Online (Sandbox Code Playgroud)
在kotlin中,似乎字符串被视为char数组,因此结果是每个字符的映射.是否有可能像我发布的swift代码一样获得类似的行为?
"Some String".map { SomeObject(it) }
Run Code Online (Sandbox Code Playgroud)
你可以用以下方法完成类似的事情let:
"Some String".let { SomeObject(it) }
Run Code Online (Sandbox Code Playgroud)
如果您有适当的构造函数(例如constructor(s : String) : this(...)),您也可以按如下方式调用它:
"Some String".let(::SomeObject)
Run Code Online (Sandbox Code Playgroud)
run并且with也可以工作,但是如果你想在它上面调用接收器的方法,通常会采用它.使用run/ with为此将如下所示:
"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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
332 次 |
| 最近记录: |