为什么我不能对此函数使用后缀表示法

时间:2017-02-27 20:46:45

标签: scala postfix

我有一个简单的功能,我想用后缀符号来调用

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抱怨Expression of type SimpleSql[Row] does not conform to expected type A_

当我尝试编译时,我收到以下错误

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

如果我将参数括在run的parens即

中,它会按预期工作
getColors(ids: Seq[UUID](implicit conn: Connection) = run(SQL"....")

1 个答案:

答案 0 :(得分:2)

对于裸方法没有postfix表示法,只对命名对象(带标识符)进行方法调用。对于具有单个参数的对象,还有方法调用的中缀表示法。

以下是使用postfix和infix表示法的方法:

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)

然而,这不起作用:

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

您可以使用中缀表示法重写它:

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

在你的情况下,你可以写:

this run SQL"""select flavor from flavors where id in $ids"""