Themerius
Themerius

Reputation: 1911

Single infix like method invocation with Scala

In Scala the dot notation is in much cases optional, like 1 + 2 equals 1.+(2).

But is it also possible, with some magic, to write also things like:

object u {
  def meth (s: String) = println(s)
  meth "str"  // as shortcut for meth("str")
}

Result:

<console>:3: error: ';' expected but string literal found.

But this would be very interesting for creating internal DSLs, if something like this works. Note: In this hypothetical question I'll don't want to draw on things like u meth "str".

Upvotes: 1

Views: 174

Answers (1)

senia
senia

Reputation: 38045

You can do something similar using string interpolation from Scala 2.10, but I don't think you should:

scala> implicit class Meth(val sc: StringContext) extends AnyVal {
     |   def meth(): String = "meth" + sc.parts(0)
     | }
defined class Meth

scala> meth"str"
res0: String = methstr

It isn't possible to use expressions like meth "str" in Scala. You can write u meth "str", "str" meth, meth"str" or meth ("str"), but not meth "str".

Upvotes: 3

Related Questions