Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin map a string to another type?

Tags:

kotlin

In swift, I can do

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

In kotlin it seems like the string is treated as a char array so the result is the map of each character. Is it possible to get similar behavior like the swift code I posted?

"Some String".map { SomeObject(it) } 
like image 267
aryaxt Avatar asked Oct 17 '25 13:10

aryaxt


2 Answers

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()
}
like image 123
Roland Avatar answered Oct 20 '25 16:10

Roland


Besides using let, run or with, you can also write an extension method:

fun String.toSomeObject() = SomeObject(this)

Then use it like follows:

"SomeObject".toSomeObject()
like image 27
m0skit0 Avatar answered Oct 20 '25 18:10

m0skit0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!