Generic string literals

Hey there,

now that we have generic number literals, is there any reason why we can’t have generic string literals too? This would for example be useful for URLs. Currently the best we can do is a string interpolator, which isn’t great because you need to remember the correct import to make that work.

2 Likes

May be the compiler option can help:

-Yimports IMPORT1,IMPORT2

Custom root imports, default is java.lang,scala,scala.Predef

I’m not sure what you are suggesting ?

It feels like most things are already covered with (string interpolators, ) the raw interpolator, and implicit conversion:

val a = url"https://contributors.scala-lang.org/t/generic-string-literals/7091"
// or
given Conversion[String, URL] = ???
val b: Url = raw"https://contributors.scala-lang.org/t/generic-string-literals/7091"

The second option avoids the “forgot to import” problem, as you can put the given on the companion object of the class, and it will be in scope automatically (?)

1 Like

I’m suggesting we add a mechanism to overload string literals similar to what we already have for numeric literals. Standard implicit conversions aren’t ideal because they also apply to non-literal expressions and because not every string is necessarily valid for the relevant type, e. g. not all strings are valid URLs.

That said, it seems to be possible to define the apply method of a Conversion with inline and have a macro parse the string and see if it’s valid. At first glance that seems viable.

1 Like

It’s possible with inline implicit def, but currently not with Conversion. This is what SIP 66 is about.