BBK#4: Spin My Words...
Don't be a Java-ish dev in Kotlin-ish world, improve your knowledge about Koltin Standard Library and write better Kotlin code. ✌🏻 If your Java dev migrating to Kotlin this will help you learn alot!
Question
: Write a function that reversed all words in the String whose length is five or more letter words reversed.
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"
Try it put yourself :
👨🏻💻👉 https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/kotlin
Java-ish Solution 1:
fun spinWords1(input:String):String{
val words = input.split(" ")
var result = ""
for (word in words) {
if(word.length > 4){
result = "$result ${word.reversed()}"
}else{
result = "$result $word"
}
}
return result
}
// Performance : took 10.4ms on my machine
I have explained issue with these approach in multiple post now, You can checkout its gist with issues with accumulator pattern and alternative approach from below article.

Solution 2:
Using Map
and JoinToString
, Checkout advance stuff we can do with it!

fun spinWords(input:String):String = input.split(" ")
.map{word-> if(word.length>5) word.reversed() else word}
.joinToString(" ")
// Performance : took 15.5ms on my machine
minute performance hit is due to Join
operation.
Solution 3:
Another advance way to use JoinToString
,
fun spinWords(input: String) = input.split(" ")
.joinToString(" ") {
if (it.length > 4) it.reversed() else it
}
// Performance : took 15.5ms on my machine
Performance is same as Solution 2
.
To learn more advance cases checkout of JoinToString
checkout

Enjoying the Post?
a clap is much appreciated if you enjoyed. No sign up or cost associated :)
If you want to support my content do consider dropping a tip/coffee/donation💰
Conclusion
Aim of these articles is not hate on Java, but to help people learn various ways in which they can write same logic better and more Kotlin standard library focused way.
Hope you find it informative and if you have any feedback or post request or want to subscribe to my mailing list forms are below.
Until next time. Happy Hacking! 👩💻
Solve Previous:

Solve Next:

Enjoying the Post?
a clap is much appreciated if you enjoyed. No sign up or cost associated :)
If you want to support my content do consider dropping a tip/coffee/donation💰