String appendIfMissing / prependIfMissing

Is there any stdlib alternative?

fun String.appendIfMissing(suffix: String) = if (endsWith(suffix)) this else (this + suffix)
fun String.prependIfMissing(prefix: String) = if (startsWith(prefix)) this else (prefix + this)

used them in almost all my projects for various purposes. Especially in places where using Path/URL is impossible/undesirable, something like path.appendIfMissing("/")

See also: Apache StringUtils

2 Likes

What do you mean by “alternative”? Those are quite short/idiomatic implementations already.

found the issue: https://youtrack.jetbrains.com/issue/KT-19805

Also see my PR, which has been pending for more than 2 years now: Strings: Add add{Prefix,Suffix}() extension functions by sschuberth · Pull Request #1591 · JetBrains/kotlin · GitHub

1 Like