Skip to content

Instantly share code, notes, and snippets.

@psteiger
Created February 13, 2019 22:28
Show Gist options
  • Save psteiger/d88cb5382923b2db77988df9cb7146d1 to your computer and use it in GitHub Desktop.
Save psteiger/d88cb5382923b2db77988df9cb7146d1 to your computer and use it in GitHub Desktop.
Reducing boilerplate with Kotlin - an example
// how to check if a string contains a number of chars?
// the java-esque way:
imageNameWithoutExtension.contains('.') ||
imageNameWithoutExtension.contains('#') ||
imageNameWithoutExtension.contains('$') ||
imageNameWithoutExtension.contains('[') ||
imageNameWithoutExtension.contains(']')
// too much repeated code.
imageNameWithoutExtension.run {
contains('.') || contains('#') || contains('$') || contains('[') || contains(']')
}
// still too much repeated code. Let's create a .containsAny using Kotlin Extension and functional programming.
fun String.containsAny(vararg chars: Char) = chars.fold(false) { acc, c -> acc || this.contains(c) }
imageNameWithoutExtension.containsAny('.', '#', '$', '[', ']')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment