Anyone else thinks it would be nice to have a `Str...
# stdlib
e
Anyone else thinks it would be nice to have a
String.prepend(value: String)
in the stdlib? I need it quite often and
.let { "prefix$it" }
doesn't express intent so well.
s
what’s wrong with something like this?
Copy code
val myString = "prefix" + getStringToPrependTo()
e
Nothing wrong, it's just that it doesn't express intent so well. For example, in my opinion this:
Copy code
fun String.normalizeHttpsUrl() =
  if (string.startsWith("https://")) this
  else this.prepend("https://")
is more human-readable than this:
Copy code
fun String.normalizeHttpsUrl() =
  if (string.startsWith("https://")) this
  else "https://$this"
(ignore the fact this is a very simple and dumb example)
m
I'd do
"https://${this.removePrefix("https://")}"
for this specific example
g
Copy code
fun String.normalizeHttpsUrl() =
  if (string.startsWith("https://")) this
  else "https://".append(this)
Just an opinion, but this reads nice too, as the parts are in the order they'll appear on the final string
👍 1
e
Thanks for your inputs. I think a better example would be when the string is nullable and a value should be prepended only when it's not null.
Copy code
val result: String? = someNullableString
  ?.doSomeTransformation()
  ?.prepend("something")
IMO it reads better than
Copy code
val result: String? = someNullableString
  ?.doSomeTransformation()
  ?.let { "something$it" }
Because for appending values it's possible without
.let
by using
.plus