Since there is a lot of talk about a new syntax for collection literals, I thought it might be time to bring up something I have been thinking about a lot lately:
It’s not fun to program inside string interpolators
Let me explain: in the JS world, there is JSX, which allows things like this:
handleOnClick = () => {
console.log("clicked");
};
button =
<button id="btn" onClick={this.handleOnClick}>
Click Here
</button>
Two thinks jump out:
- Code is injecting things into another language
- There is syntax highlighting
Here is an hypothetical equivalent in Scala:
def handleOnClick() =
console.log("clicked");
val button =
html"""<button id="btn" onClick=${handleOnClick}>
Click Here
</button>"""
We still have the ability to insert things into other contexts, but the syntax highlighting is gone
So let’s do the same !
Small issue:
- There’s one JS_, whereas there’s an arbitrary amount of string interpolators, for an arbitrary number of target languages
Here are the obvious (to me) solutions:
- magic: Compile and run a syntax highlighter at compile-time
- markdown: Use whatever syntax highlighter is present on the host machine
# Example
```scala
def f[T](x: T): T
```
Well it doesn't quite work in markdown inside markdown, but if you remove one layer it does, it's what this forum runs on !
Why am I speaking about this now ?
Well because it would help solving the “we need to define bulk data locally” problem that the new collection syntax aims to solve:
val people: List[Person] = json"""
[
{ name = "John"},
{ name = "Paula"},
{ name = "Rain"},
]
""".asScalaCollection
Of course this is much more ambitious and powerful, but at the same time, in a way it doesn’t touch the language at all: not its syntax, not its semantics, only its tooling
It’s also a good excuse to put some compiler engineers to work on tooling, which seems like it might be a good thing:
It’s also the kind of crazy ideas that get stolen by other languages later
And it won’t be like the ones that didn’t, looking at you XML literals, as it’s not even syntax, only tooling, it doesn’t even have to be specced outside of “Highlighter[magic]
is reserved for that purpose with no guarantee”