2017-02-27 118 views
0

我有一个简单的功能,我想用后缀符号来调用为什么我不能使用后缀符号此功能

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预期,即

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

回答

2

没有这样的事情作为裸方法的后缀表示法,只有命名对象(带标识符)的方法调用。对于具有单个参数的对象的方法调用也有中缀表示法。

这里有方法可以使用后缀和中缀表示法与方法:

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"""