After the announcement last year, that Google are now endorsing Kotlin as an official language for Android, there followed the inevitable avalanche of Kotlin blog posts.
So what is left to say about this new language that hasn’t already been said? Not a lot to be frank!
However, one thing I’ve not seen written about too much is the large number of nice little convenience functions built in to the Kotlin Standard Library.
If you choose Kotlin as your language you get many helpful convenience functions built right in to the language. Things that, in the past would have required a developer to spend time and effort to implement and also repackage in some way if they wanted to re-use them in a different project.
In this post I’ll take a look at what can be done to make your life, working with Strings, more pleasant.
If the string you apply this call in, contains the value passed in, it returns you the contents of the string after that character, otherwise it returns the original string.
val filename = “hello.txt”
This is accompanied by other similar functions like substringBefore , substringBeforeFirst and others so I recommend you play around and discover these.
If you think this might be a kotlin equivalent of toUpperCase you’d be wrong, it’s nicer than that, It capitalizes the first letter of the string you call it on. If the string already starts with a capital, its work is done!
val firstName = “brian”
As you’d imagine, it has a companion called decapitalize which works in the opposite way.
Take the string and drops the last ‘n’ characters
val someText = “useful info with garbage on the end—“
prints: ‘useful info with garbage on the end’
Accompanied by other similar functions like dropWhile, dropLastWhile and others, have a play!
val dirtyText = “***Some dirty and difficult to read text***”
prints: ‘Some dirty and difficult to read text’
And to take it one step further, you can specify separate prefixes and suffixes to remove.
val html = “<h2>Web Page Title</h2>”
prints: ‘Web Page Title’
How cool is that?
I recommend you spend some time playing around for yourself, who knows what you will find!