user228534
user228534

Reputation:

Use '_' in map for string interpolation

I have a List[String], and I want to quote each element. So I figured I could just do var.map(s"'$_'"). But that gives me error in interpolated string: identifier or block expected. What am I doing wrong? Is there a way to use the _ within a string interpolation?

I'm currently doing var.map("'" + _ + "'"), but it seems somewhat verbose and confusing.

Upvotes: 4

Views: 1004

Answers (2)

som-snytt
som-snytt

Reputation: 39587

The PR to make this work wasn't merged because the syntax was considered too radical, too unsettling.

The PR for the same syntax in a pattern context was accepted, however.

There is some discussion at:

https://github.com/scala/scala/pull/2793

I would have used this syntax at least a handful of times. People like to save an extra arrow. People also don't like the burden of inventing identifiers needlessly. Yes, like x.

Upvotes: 8

dhg
dhg

Reputation: 52701

I would do:

var.map(x => s"'$x'")

It is decidedly less "verbose and confusing", and probably less confusing than var.map(s"'$_'") as well.

Upvotes: 6

Related Questions