gpt4 book ai didi

Kotlin 将字符串映射到另一种类型?

转载 作者:行者123 更新时间:2023-12-01 09:44:04 24 4
gpt4 key购买 nike

在swift中,我可以做到

"Some String".map { SomeObject($0) } 

在 kotlin 中,字符串似乎被视为 char 数组,因此结果是每个字符的映射。是否有可能获得与我发布的 swift 代码类似的行为?

"Some String".map { SomeObject(it) } 

最佳答案

您可以使用 let 完成类似的操作:

"Some String".let { SomeObject(it) }

如果您有适当的构造函数(例如 constructor(s : String) : this(...)),您也可以按如下方式调用它:

"Some String".let(::SomeObject)

runwith也可以工作,但如果您想在其上调用接收者的方法,通常会采用。为此使用 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()
}

关于Kotlin 将字符串映射到另一种类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52992313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com