Colton Idle
08/05/2021, 4:22 PMfun formatPhoneNumber(original: String): String {
var number = original
number =
number.dropLast(4) +
"-" +
number.substring(
number.length - 4,
number.length,
)
number =
number.substring(0, number.length - 8) +
")" +
number.substring(
number.length - 8,
number.length,
)
(number.dropLast(12) +
"(" +
number.substring(
number.length - 12,
number.length,
)).also { number = it }
return number
}
Ruckus
08/05/2021, 4:27 PMfun formatPhoneNumber(original: String) = buildString {
append('(')
append(original.substring(0, 3))
append(") ")
append(original.substring(3, 6))
append('-')
append(original.substring(6, 10))
}
Colton Idle
08/05/2021, 4:28 PM<http://com.google.common.io|com.google.common.io>.Files.append
?Colton Idle
08/05/2021, 4:32 PMfun formatPhoneNumber(original: String) = buildString {
append('(')
append(original.substring(0, 3))
append(") ")
append(original.substring(3, 6))
append('-')
append(original.substring(6, 10))
}
This does look way better than the original. cheersRuckus
08/05/2021, 4:40 PMColton Idle
08/05/2021, 5:23 PMMatteo Mirk
08/06/2021, 7:12 AMval numberGroups = """(\d{3})(\d{3})(\d{4})""".toRegex()
fun formatPhoneNumber(original: String) = original.replace(numberGroups, "($1) $2-$3")
Matteo Mirk
08/06/2021, 7:13 AMthanksforallthefish
08/06/2021, 7:29 AMColton Idle
08/06/2021, 7:47 AMMatteo Mirk
08/06/2021, 8:10 AMKlitos Kyriacou
08/09/2021, 3:16 PMbuildString
was chosen in the answer above instead of a simple string concatenation operator?
fun formatPhoneNumber(original: String) =
"(" + original.substring(0, 3) + ") " + original.substring(3, 6) + "-" + original.substring(6, 10)
Is there a performance-related reason or is it just more idiomatic?Matteo Mirk
08/09/2021, 3:58 PMbuildString()
gives you a DSL over a StringBuilder
instance. Your code allocates 7 temporary strings before creating the final one. Of course its weight is negligible if āoriginalā is short and the function isnāt executed in a hot loop or thousands time/sec. But anyway using that function, or a template string would be more idiomatic Kotlin.Klitos Kyriacou
08/09/2021, 4:07 PMbuildString
? In Java, stringA + stringB + stringC
performs just as fast as using StringBuilder
because the Java compiler generates the same bytecode, without creating any intermediate temporary string objects. It used to generate intermediate strings back in the days before Java 1.7. If Kotlin generates intermediate strings, doesn't this sound a little like a backward step?Matteo Mirk
08/09/2021, 4:17 PM"(${original.substring(0, 3)}) ${original.substring(3, 6)}-${original.substring(6, 10)}"
But in this case I prefer best my solution š https://kotlinlang.slack.com/archives/C09222272/p1628233961007000?thread_ts=1628180541.005400&cid=C09222272thanksforallthefish
08/10/2021, 5:31 AMO(n^2)
) until you donāt need to care.
also why I am still not fully sold on multiplatform, but I really really need to try harder and more seriously