Skip to content

Instantly share code, notes, and snippets.

@mukandrew
Created September 23, 2023 22:01
Show Gist options
  • Save mukandrew/900e31f8aae1ecdb27d19993517e37a4 to your computer and use it in GitHub Desktop.
Save mukandrew/900e31f8aae1ecdb27d19993517e37a4 to your computer and use it in GitHub Desktop.
MapDelegate from SnakeCase property Name
/**
* 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