This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Expression placeholder for Strings??

20 replies
maku
Joined: 2008-10-06,
User offline. Last seen 4 years 4 weeks ago.

Hi,

I'm new in Scala and I'm wondering if there it is not possible to use a
placeholder for expressions in strings (like in scala xml)
I found nothing in this context...

e.g.
val myVal="That's it"
println("My Val ${myVal}")

Could anybody give me a hint?

TIA
Martin

Chris Twiner
Joined: 2008-12-17,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

Is

println("My Val " +myVal)

ok? "Most" objects in scala will have sensible defaults for toString
which is being called in the above example. You can override this
function for your own classes (and via mixins some existing classes).

On Tue, Mar 17, 2009 at 11:12 AM, Martin Kuhn wrote:
>
> Hi,
>
> I'm new in Scala and I'm wondering if there it is not possible to use a
> placeholder for expressions in strings (like in scala xml)
> I found nothing in this context...
>
> e.g.
> val myVal="That's it"
> println("My Val ${myVal}")
>
> Could anybody give me a hint?
>
> TIA
> Martin
>
>
> --
> View this message in context: http://www.nabble.com/Expression-placeholder-for-Strings---tp22556004p22...
> Sent from the Scala - User mailing list archive at Nabble.com.
>
>

Patrick Wright
Joined: 2009-01-14,
User offline. Last seen 31 weeks 5 days ago.
Re: Expression placeholder for Strings??

You can use the Formatter[1] and String.format()[2] support

>scala
Welcome to Scala version 2.7.3.final (Java HotSpot(TM) Server VM, Java
1.6.0_12).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import java.lang.String.format
import java.lang.String.format

scala> val myVal = "That's it"
myVal: java.lang.String = That's it

scala> println(format("My Val %s", myVal))
My Val That's it

Formatter supports features similar to printf in C, with formatting
for dates, numbers, strings, alignment, etc.

Patrick

1- http://tinyurl.com/2kur9z
2- http://tinyurl.com/c4k7y8

Stepan Koltsov
Joined: 2008-12-20,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

On Tue, Mar 17, 2009 at 13:12, Martin Kuhn wrote:
>
> I'm new in Scala and I'm wondering if there it is not possible to use a
> placeholder for expressions in strings (like in scala xml)
> I found nothing in this context...
>
> e.g.
> val myVal="That's it"
> println("My Val ${myVal}")
>
> Could anybody give me a hint?

I use the following trick:

===
class StringExtras(string: String) {
def % (args: Any*) =
String.format(string, args.toArray.asInstanceOf[Array[Object]]: _*)
}

implicit def stringExtras(string: String) = new StringExtras(string)

scala> "%s, %s" % ("hello", "world")
res2: java.lang.String = hello, world

scala> "distance = %.2f km" % (7234.12123)
res3: java.lang.String = distance = 7234.12 km
===

S.

Karsten Breit
Joined: 2009-03-11,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??
Hi Martin,

lately I accidently stumbled upon this blog post: http://www.familie-kneissl.org/Members/martin/blog/a-scala-wrapper-for-apache-velocity

That guy is using the velocity template engine to get what you're longing for.

Cheers,
Karsten
Am 17.03.2009 um 11:12 schrieb Martin Kuhn:

Hi,

I'm new in Scala and I'm wondering if there it is not possible to use a
placeholder for expressions in strings (like in scala xml)
I found nothing in this context...

e.g.
val myVal="That's it"
println("My Val ${myVal}")

Could anybody give me a hint?

TIA
Martin


--
View this message in context: http://www.nabble.com/Expression-placeholder-for-Strings---tp22556004p22556004.html
Sent from the Scala - User mailing list archive at Nabble.com.


odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Expression placeholder for Strings??

I usually don't write spaces around +'s when used as string
concatenation. With this convention note that

"prefix "+expr+" suffix"

is one character longer than the proposed alternative

"prefix ${expr} suffix"

Is that one character savings worth any extra complication in lexical syntax?

Cheers

DRMacIver
Joined: 2008-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

2009/3/17 martin odersky :
> I usually don't write spaces around +'s  when used as string
> concatenation. With this convention note that
>
> "prefix "+expr+" suffix"
>
> is one character longer than the proposed alternative
>
> "prefix ${expr} suffix"
>
> Is that one character savings worth any extra complication in lexical syntax?

Actually, yes. Even ignoring the fact that I find the ${ } approach a
lot more readable (though ${ } would be a poor choice in my opinion as
it conflicts with standard templating engines on the JVM), the case
where + is a huge pain point is when you have multiline strings.
"""+expr+""" is suddenly a lot less appealing in comparison.

Ishaaq Chandy
Joined: 2009-02-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??
The difference could possibly be in lazy evaluation, i.e. you could get
"prefix ${expr} suffix" to get expanded only when you need it. Which implies that something like this...

logger.debug("prefix ${callSomeIncrediblyComplexFunction()} suffix")

...does not evaluate unless your debug settings have been turned on.Whereas something like this...

logger.debug("prefix "+callSomeIncrediblyComplexFunction()+"suffix")

...would get evaluated every time.

Of course, I have no idea whether or not something like this is even possible in a statically typed way.

Ishaaq


2009/3/18 martin odersky <martin.odersky@epfl.ch>
I usually don't write spaces around +'s  when used as string
concatenation. With this convention note that

"prefix "+expr+" suffix"

is one character longer than the proposed alternative

"prefix ${expr} suffix"

Is that one character savings worth any extra complication in lexical syntax?

Cheers

odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Expression placeholder for Strings??

On Wed, Mar 18, 2009 at 12:23 AM, David MacIver wrote:
> 2009/3/17 martin odersky :
>> I usually don't write spaces around +'s  when used as string
>> concatenation. With this convention note that
>>
>> "prefix "+expr+" suffix"
>>
>> is one character longer than the proposed alternative
>>
>> "prefix ${expr} suffix"
>>
>> Is that one character savings worth any extra complication in lexical syntax?
>
> Actually, yes. Even ignoring the fact that I find the ${ } approach a
> lot more readable (though ${ } would be a poor choice in my opinion as
> it conflicts with standard templating engines on the JVM), the case
> where + is a huge pain point is when you have multiline strings.
> """+expr+""" is suddenly a lot less appealing in comparison.
>
True. But """ """ are raw strings without any escapes. It seems weird
to make an exception for an escape of embedded exceptions but allow no
other escapes in these strings.

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Expression placeholder for Strings??

On Wed, Mar 18, 2009 at 12:27:49AM +0100, martin odersky wrote:
> True. But """ """ are raw strings without any escapes. It seems weird
> to make an exception for an escape of embedded exceptions but allow no
> other escapes in these strings.

I have a nifty idea here that might make everyone happy and solve a
number of other semi-related problems, but first I have to um finish
rewriting the parser.

Jon Pretty
Joined: 2009-02-02,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

Hi David,

David MacIver wrote:
> Actually, yes. Even ignoring the fact that I find the ${ } approach a
> lot more readable (though ${ } would be a poor choice in my opinion as
> it conflicts with standard templating engines on the JVM), the case
> where + is a huge pain point is when you have multiline strings.
> """+expr+""" is suddenly a lot less appealing in comparison.

The "${foo}" approach has the added benefit that the matched braces tend
to direct the eyes inwards towards the expression.

XML provides a reasonable alternative.

Here is a multiline string.
{foo}.
.text

It's ugly, but it works. In the less immediate term, the syntax could
probably be improved[1].

Jon

[1] Probably along with some other XML updates, such as a more concise
replacement for .

DRMacIver
Joined: 2008-09-02,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

2009/3/17 Jon Pretty :
> Hi David,
>
> David MacIver wrote:
>> Actually, yes. Even ignoring the fact that I find the ${ } approach a
>> lot more readable (though ${ } would be a poor choice in my opinion as
>> it conflicts with standard templating engines on the JVM), the case
>> where + is a huge pain point is when you have multiline strings.
>> """+expr+""" is suddenly a lot less appealing in comparison.
>
> The "${foo}" approach has the added benefit that the matched braces tend
> to direct the eyes inwards towards the expression.
>
> XML provides a reasonable alternative.
>
>  
>     Here is a multiline string.
>     {foo}.
>   .text
>
> It's ugly, but it works.  In the less immediate term, the syntax could
> probably be improved[1].

Well, yes. But um, yuck. :-)

maku
Joined: 2008-10-06,
User offline. Last seen 4 years 4 weeks ago.
Re: Expression placeholder for Strings??

kabtain wrote:
>
> Hi Martin,
>
> lately I accidently stumbled upon this blog post:
> http://www.familie-kneissl.org/Members/martin/blog/a-scala-wrapper-for-a...
>
> That guy is using the velocity template engine to get what you're
> longing for.
>
>

Hi Karsten,

Thanks for the hint. I found this post already. But my point of view is that
such a powerfull language like scala should provide such a functionality.

Because of Scala should be used also for scripting purposes. In this context
I don't want to work with third party libs.

Regards,

Russel Winder
Joined: 2009-02-13,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

Martin,

On Wed, 2009-03-18 at 00:16 +0100, martin odersky wrote:
> I usually don't write spaces around +'s when used as string
> concatenation. With this convention note that
>
> "prefix "+expr+" suffix"
>
> is one character longer than the proposed alternative
>
> "prefix ${expr} suffix"
>
> Is that one character savings worth any extra complication in lexical syntax?

Saving characters is not the issue here, the issue is the mapping of
concept to readable rendering. The issue of "lexical syntax" is both a
compilation and syntax tree processing thing -- which is more
complicated as you say -- and it is a readability issue. Readability
here is about human parsing and perception, which is very different from
issues of grammars, parsers and compilers in the transforming of source
code to bytecodes.

The message here is I think that there are a group of Scala users who
prefer a way of doing things available in other languages and are
prepared to say so.

If the Scala team wish to say "it isn't going to happen" on this issue
then fine, that is a choice. I would though rather not see specious and
sophistic argumentation -- at least not without a smiley being shown.

Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Expression placeholder for Strings??

> 2009/3/17 martin odersky :
> > I usually don't write spaces around +'s  when used as string
> > concatenation. With this convention note that
> >
> > "prefix "+expr+" suffix"
> >
> > is one character longer than the proposed alternative
> >
> > "prefix ${expr} suffix"
> >
> > Is that one character savings worth any extra complication
> in lexical syntax?
>
> Actually, yes. Even ignoring the fact that I find the ${ } approach a
> lot more readable (though ${ } would be a poor choice in my opinion as
> it conflicts with standard templating engines on the JVM), the case
> where + is a huge pain point is when you have multiline strings.
> """+expr+""" is suddenly a lot less appealing in comparison.
>

The expression "prefix "+expr+" suffix" is in my eyes much more
noisy than prefix ${expr} suffix (and I have a lot of experience
with both).

Well, that *may* be in the eye of the beholder.

BUT:
I do not like mentioning language constructs in combination with
IDE's but in this case it indeed makes a difference if you
work with syntax highlighting.

While "prefix ${expr} suffix" is chunked as 'one string expression',
"prefix "+expr+" suffix" results in a confusing switch of colors,
which needs much more concentration to be grokked when scanning
some code.

milessabin
Joined: 2008-08-11,
User offline. Last seen 33 weeks 3 days ago.
Re: Expression placeholder for Strings??

On Wed, Mar 18, 2009 at 8:47 AM, Detering Dirk
wrote:
> While "prefix ${expr} suffix" is chunked as 'one string expression',
> "prefix "+expr+" suffix" results in a confusing switch of colors,
> which needs much more concentration to be grokked when scanning
> some code.

If we adopted syntax of this form then I would expect all the IDEs
will support differential colouring of any embedded expressions.

I'd also expect them to offer the option of having the colouring of
embedded expressions be the same as the surrounding string literal if
that's what you really want.

Cheers,

Miles

Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Expression placeholder for Strings??

> Karsten Breit wrote:
> lately I accidently stumbled upon this blog post:
> http://www.familie-kneissl.org/Members/martin/blog/a-scala-wra
> pper-for-apache-velocity
>
> That guy is using the velocity template engine to get what
> you're longing for.

Well, in my opinion that is coming from the wrong end...

You can use an in-string-expression approach for
very simple templating tasks and perhaps scale up to
more complicated scenarios.
( The G-String approach )
Somewhere you reach the point where you decide that a
real template engine is the better thing.
(Here comes velocity, or better Groovy template engines).

But to demand a third party lib, instanciation of
a template engine, put in bindings and calling a merge
to solve even the most simplest of all this scenarios
seems to me absolutely wrong.

Compare:

"Hello ${yourname}. My name is ${myname}!".merge( someKindOfMap )

With:
"Hello "+yourname+". My name is"+myname+"!"

Then even the current way is better. It is shorter and does not
involve the third-party-interpreter-engine-with-AST-in-memory.

Compare:

val template: Template = "Hello ${yourname}. My name is ${myname}!"
people foreach { person =>
println(template.merge('yourname->person.name, 'myname->"Martin") }

With:

def template(yourname:String, myname:String) = {
"Hello "+yourname+". My name is "+myname+"!" }

people foreach { person => println (template(person.name, "Martin") ) }

Then you see that the application of the template is much clearer.

The velocity wrapper is OK, in use cases where velocity would naturally
be used. But not as in-string-expression replacement.

KR
Det

PS:
It was really an effort to avoid mentioning that #foreach example ...

Detering Dirk
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
RE: Expression placeholder for Strings??

Miles,

> If we adopted syntax of this form then I would expect all the IDEs
> will support differential colouring of any embedded expressions.
>
> I'd also expect them to offer the option of having the colouring of
> embedded expressions be the same as the surrounding string literal if
> that's what you really want.

If you don't adopt this syntax, there's no chance for sensible
highlight options, particularly not the latter ;-) .

If you adopt this syntax, different highlighting is a
requirement worth to think about.
The current Eclipse Velocity plugin does this, and it is good.
It seems the Groovy plugin does not do it, and I never missed it
until I now looked for it.

The reason may be that I mostly think of "Name: ${name}"
as 'the output text' and not 'a string with fix and variable parts'.
So I'm interested in the variables/expressions mostly when I write
or actively maintain them, but not when I scan them only as part of
their surrounding context, what happens more often.

KR
Det

odersky
Joined: 2008-07-29,
User offline. Last seen 45 weeks 6 days ago.
Re: Expression placeholder for Strings??

On Wed, Mar 18, 2009 at 8:39 AM, Russel Winder
wrote:
> Martin,
>
> On Wed, 2009-03-18 at 00:16 +0100, martin odersky wrote:
>> I usually don't write spaces around +'s  when used as string
>> concatenation. With this convention note that
>>
>> "prefix "+expr+" suffix"
>>
>> is one character longer than the proposed alternative
>>
>> "prefix ${expr} suffix"
>>
>> Is that one character savings worth any extra complication in lexical syntax?
>
> Saving characters is not the issue here, the issue is the mapping of
> concept to readable rendering.  The issue of "lexical syntax" is both a
> compilation and syntax tree processing thing -- which is more
> complicated as you say -- and it is a readability issue.  Readability
> here is about human parsing and perception, which is very different from
> issues of grammars, parsers and compilers in the transforming of source
> code to bytecodes.

Indeed saving characters is not the issue. It's reader perception. I
just would like to encourage
everyone to try writing +'s without spaces around them, or just write
a space between the + and the embedded expression but _not_ between
the + and the string quote. After a while you appreciate that strings
with embedded fields become much more readable. Compare the three
strings below.

"Finished processing of "+count+" items."
"Finished processing of "+ count +" items."
"Finished processing of " + count + " items."

(Probably you need to copy first into a buffer with non-proportional
fonts to really appreciate the difference). The first two alternatives
read well, IMO. The last one, which people usually use, is clearly the
worst, because it distorts formatting most and emphasizes the +'s
which are the least important aspect of the string. Regarding syntax
highlighting, I'd argue expressions embedded in strings should in any
case be colored differently than the characters around them.
Furthermore, as Miles says, it's easy to apply whatever syntax
highlighting scheme is desired to embedded +'s as well. If I can
suggest a coloring, I would code the pluses that are directly adjacent
to a string quote the same color as the string. The plus then becomes
almost invisible and you really see three items that follow each
other, without paying attention to the operator that connects them.
That's as it should be. A string embedding, after all, is a
lightweight concatenation, nothing more. That makes it fundamentally
different from an embedding into an XML literal.

Cheers

milessabin
Joined: 2008-08-11,
User offline. Last seen 33 weeks 3 days ago.
Re: Expression placeholder for Strings??

On Wed, Mar 18, 2009 at 10:46 AM, martin odersky wrote:
> Furthermore, as Miles says, it's easy to apply whatever syntax
> highlighting scheme is desired to embedded +'s as well. If I can
> suggest a coloring, I would code the pluses that are directly adjacent
> to a string quote the same color as the string. The plus then becomes
> almost invisible and you really see three items that follow each
> other, without paying attention to the operator that connects them.

I like that suggestion :-)

Cheers,

Miles

Andrew Foggin
Joined: 2009-03-18,
User offline. Last seen 42 years 45 weeks ago.
Re: Expression placeholder for Strings??

Paul Phillips wrote:
> I have a nifty idea here that might make everyone happy and solve a
> number of other semi-related problems, but first I have to um finish
> rewriting the parser.
>
>
Good luck with that ;)

B.T.W. I posted a working proof-of-concept compiler plug-in that
included expression placeholders more than a year ago:

http://www.nabble.com/-scala--Extending-Scala-td15856708.html

Didn't get much response though. And parser support for embedded
grammars would be even better...

Regards,

Andrew Foggin

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland