2017-02-27 117 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"""