Skip to content

Instantly share code, notes, and snippets.

@ktprezes
Last active July 9, 2022 21:49
Show Gist options
  • Save ktprezes/9f7e1a33bdb4cb8a814dabad107f10e1 to your computer and use it in GitHub Desktop.
Save ktprezes/9f7e1a33bdb4cb8a814dabad107f10e1 to your computer and use it in GitHub Desktop.
Kotlin - splitting a string into individual characters
val string: String = "abcd"
val splitString: List<String> = string.map { it.toString() }
/*
EXPLANATION:
A) In Java, the output of the code:
String str = "abcd";
String[] splitString = str.split("");
System.out.println(Arrays.toString(splitString));
System.out.println(splitString[0].getClass());
System.out.println(splitString.length);
is:
[a, b, c, d] // original string is split into _array_ of strings
class java.lang.String
4 // length of the resulting array
B) In Kotlin, the output of the naive-translation-of-java-code:
val str = "abcd"
val splitString: List<String> = str.split("")
println(splitString)
println(splitString[0]::class.qualifiedName)
println(splitString.size)
is: // original string is split into _list_ of strings AND
[, a, b, c, d, ] // first and last element of this list are "" (empty strings)
kotlin.String
6 // length of the resulting list
THUS,
to get the result similar to the java code,
one should use: str.map { it.toString() }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment