Created
September 23, 2023 22:01
-
-
Save mukandrew/900e31f8aae1ecdb27d19993517e37a4 to your computer and use it in GitHub Desktop.
MapDelegate from SnakeCase property Name
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
/** | |
* To use delegate property from map, getting value from a snakeCase key | |
* | |
* eg.: | |
* ```kotlin | |
* val myMap = mapOf("hello_world" to "Some Value") | |
* val helloWorld: String by myMap.fromSnakeCase() | |
* ``` | |
* | |
* So, the val "helloWorld" will contain "Some Value" | |
*/ | |
@Suppress("UNCHECKED_CAST") | |
fun <T, T1 : T> Map<String, T>.fromSnakeCase() = ReadOnlyProperty<Nothing?, T1> { _, property -> | |
this[property.name.fromCamelCaseToSnackCase()] as T1 | |
} | |
/** | |
* Transform a string written as camelCase to snakeCase | |
* | |
* eg.: | |
* ```kotlin | |
* val myValue = "helloWorld".fromCamelCaseToSnackCase() | |
* ``` | |
* | |
* So, the val "myValue" will contain "hello_world | |
*/ | |
fun String.fromCamelCaseToSnackCase(): String { | |
return buildString { | |
var prevIsUpperCase = false | |
for (char in this@fromCamelCaseToSnackCase) { | |
prevIsUpperCase = if (char.isUpperCase()) { | |
if (!prevIsUpperCase) { | |
append('_') | |
append(char.lowercase()) | |
} else { | |
append(char) | |
} | |
true | |
} else { | |
append(char) | |
false | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment