Hello, World! Isn't there a version of `String.map...
# announcements
b
Hello, World! Isn't there a version of
String.map
fun that returns a String (instead of the generic one returning a List<R>) somewhere?
I guess I can use
.toCharArray().concatToString()
... 🙂
a
somestring.let { s -> someOtherstring }
? return whatever you want from let, it could also be the same data
s
I think you could make something work with fold actually
n
you can just do .map.joinToString can't you
actually joinToSTring already takes a transforming function
Copy code
"hello".toList().joinToString { it.toUpperCase() }
I'm actually not sure why the toList is necessary
s
because
joinToString()
is defined on Iterable rather than String or CharSequence
n
Yeah, just realized, the map on CharSequence is a separate thing
this obviously begs the question why CharSequence is its own thing or at least why does CharSequence not at least inherit from Iterable<Char>
Or Sequence<Char>
My past experience is that every time I see something like this that makes no sense the answer is "because Java" so I'll assume that this is the reason here
b
sorry I wasn't very clear! My need was to map chars inside a String to other chars (my specific case: making a String suitable for a file name, so each illegal character is replaced with a space.)
I ended up doing this:
Copy code
fun String.asValidFatFileName(): String = map { if (it.isValidFatFileNameChar()) it else ' ' }.toCharArray().concatToString()
but originally I was a bit surprised that
Copy code
fun String.asValidFatFileName(): String = map { if (it.isValidFatFileNameChar()) it else ' ' }
wasn't enough
n
yeah, the string API is IMHO hugely confusing
.filter returns a string but .map returns a List<Char> 😞
anyway just add
joinToString(separator="")