Created
February 13, 2019 22:28
-
-
Save psteiger/d88cb5382923b2db77988df9cb7146d1 to your computer and use it in GitHub Desktop.
Reducing boilerplate with Kotlin - an example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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