Jason Jason -4 years ago 101
Scala Question

Why can't I use postfix notation for this function

I have a simple function that I'd like to call using postfix notation

import anorm._
class SimpleRepository {
private def run(sql: SimpleSql[Row]) = sql.as(SqlParser.scalar[String].*)

// this is how i'd like to call the method
def getColors(ids: Seq[UUUID])(implicit conn: Connection) = run SQL"""select color from colors where id in $ids"""

def getFlavors(ids: Seq[UUID])(implicit conn: Connection) = run SQL"""select flavor from flavors where id in $ids"""
}


IntelliJ complains that
Expression of type SimpleSql[Row] does not conform to expected type A_


When I try to compile I get the following error

...';' expected but string literal found.
[error] run SQL"""....


It works as expected if I enclose the parameter to
run
in parens i.e.

getColors(ids: Seq[UUID](implicit conn: Connection) = run(SQL"....")

Answer Source

There is no such thing as postfix notation for bare methods, only method calls on named objects (with identifiers). There is also infix notation for method calls on objects with single parameters.

Here are the ways you can use postfix and infix notation with methods:

case class Foo(value: String) {
    def run() = println("Running")
    def copy(newValue: String) = Foo(newValue)
}

scala> val foo = Foo("abc")
foo: Foo = Foo(abc)

scala> foo run() // Postfix ops in an object `foo`, but it is 
Running          // recommended you enable `scala.language.postfixOps`

scala> foo copy "123" // Using copy as an infix operator on `foo` with "123"
res3: Foo = Foo(123)

This however, does not work:

case class Foo(value: String) {
    def copy(newValue: String) = Foo(newValue)
    def postfix = copy "123" // does not work
}

You can re-write it using infix notation, though:

case class Foo(value: String) {
    def copy(newValue: String) = Foo(newValue)
    def postfix = this copy "123" // this works
}

In your case, you can write:

this run SQL"""select flavor from flavors where id in $ids"""
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download