What is the best way to convert pascal case string...
# announcements
i
What is the best way to convert pascal case string into snake case string in Kotlin?
"apiBaseUrl"  -> "api_base_url"
p
Split, map with capitalize, join?
i
My issue is with splitting 🤔
r
p
Oh, the inverse.
k
Copy code
str.split("(?=[A-Z])".toRegex()).joinToString("_") { it.toLowerCase() }
p
Copy code
fun String.pascalToSnakeCase() = map { char ->
        if (char.isUpperCase()) "_${char.toLowerCase()}" else char
    }.joinToString("")
👍 1
s
Copy code
"camelCase".split(Regex("(?=[A-Z])")).joinToString(separator = "_", transform = String::toLowerCase)
👍 1
j
I guess this might be considered less idiomatic:
Copy code
val capitalRegex = "([A-Z])".toRegex()

    fun String.snakify() = this.replace(capitalRegex) {
        '_' + it.value.toLowerCase()
    }.trim('_')

    @Test
    fun `test pascalToSnake`() {
        "".snakify() shouldBe ""
        "abc".snakify() shouldBe "abc"
        "aBc".snakify() shouldBe "a_bc"
        "someThingElse".snakify() shouldBe "some_thing_else"
    }
k
Looks like
Copy code
str.split(Regex("(?=[A-Z])")).joinToString("_", String::toLowerCase)
compiles with the new type inference but not the old one, that's great!
i
thanks @karelpeeters. This is exactly what I was missing. I am using old type interface (I guess) with kotling-gardle-dsl, but after small modification I made it work
Copy code
str.split(Regex("(?=[A-Z])")).joinToString("_") { it.toLowerCase() }
👍 1
BTW @karelpeeters can you drop some link related to Kotlin
old/new type inference
? What is the state - is it currently released, experimental?
k
Here's the announcement that they turned it on in the IDE but not the actual compilation: https://blog.jetbrains.com/kotlin/2019/06/kotlin-1-3-40-released/
👍 1
167 Views