BBK#1: Find Middle Element
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
: Print middle character of a string, if even print middle two characters else middle character
Try it put yourself :
π¨π»βπ»π https://www.codewars.com/kata/56747fd5cb988479af000028/train/kotlin
Solution 1:
fun getMiddle(word : String) : String {
val chars = word.toCharArray()
val mid = chars.size/2
return if(chars.size%2==0){
"${chars.get(mid-1)}${chars.get(mid)}"
}else{
"${chars.get(mid)}"
}
}
Solution 2:
Using drop
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/drop.html
fun getMiddle(word : String) : String {
val worldLength = (word.length - 1) / 2
return word.drop(worldLength).dropLast(worldLength)
}
Solution 3:
Using substring + ranges
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/substring.html
fun getMiddle(word: String): String = word
.substring((word.length-1)/2 .. word.length/2)
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 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π°