2015-06-19 188 views
0
object BugFixProject { 

    def main (args: Array[String]) { 
    val repoWithEntities = Seq(
     (ARepo, Seq(A("", ""), A("", ""))), 
     (BRepo, Seq(B("", ""), B("", ""))) 
    ) 

    printall(repoWithEntities) 
    } 

    def printall[Entity](pairs: Seq[(BaseRepo[Entity], Seq[Entity])]) : Seq[String] = { 
    pairs.map { t => 
     val repo = t._1 
     val entities = t._2 

     entities.map(repo.toString(_)) 
    }.flatten 
    } 

} 

case class A(foo: String, bar: String){} 
case class B(foo: String, bar: String){} 

trait BaseRepo[X] { 
    def toString(x: X) : String = x.toString 
} 

object BRepo extends BaseRepo[B] {} 
object ARepo extends BaseRepo[A] {} 

printall應該像主要方法中所述的那樣使用。但後來我在編譯過程中出現以下錯誤:斯卡拉動態類型

Error:(12, 9) no type parameters for method printall: (pairs: Seq[(BaseRepo[Entity], Seq[Entity])])Seq[String] exist so that it can be applied to arguments (Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])]) 
--- because --- 
argument expression's type is not compatible with formal parameter type; 
found : Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])] 
required: Seq[(BaseRepo[?Entity], Seq[?Entity])] 
     printall(repoWithEntities) 
     ^

而且

Error:(12, 18) type mismatch; 
found : Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])] 
required: Seq[(BaseRepo[Entity], Seq[Entity])] 
     printall(repoWithEntities) 
       ^

我不明白的錯誤消息。是否有可能在

def printall[Entity] 

實體只能是1特定類型?

+1

如果您知道進入方法的內容,則不需要「實體」類型參數。你在這裏試圖做什麼並不是很清楚,你有沒有嘗試重寫代碼以使其更清晰? –

+0

姆赫。我不知道如何澄清... 我想用'repoWithEntities'調用'printall',但不知道方法簽名的外觀如何... 'printall'應該可以調用一個值類型爲'Seq [(BaseRepo [Entity],Seq [Entity])]',其中「Entity」僅表示一個Tuple必須包含一個具有相同類型序列的BaseRepo。如示例中所示,repoWithEntities可以具有包含不同類型的不同回收的元組。 –

+0

在對'printall'的任何單個調用中,是的,'Entity'必須是特定類型的。 –

回答

0

嘗試使你的函數調用在一個非常通用的方式如下圖所示

def printall(pairs: Seq[(BaseRepo[_], Seq[_])]) : Seq[String] = { 

這樣,您就能夠調用printall方法有兩種BRepoARepo對象。

+0

但是這樣就有可能在'printall'中有一對'(ARepo,Seq(B(「,」,「)))'不應該被允許。這可能是您的解決方案無法編譯的原因。 –