为什么我不能写`List [I]`但是可以写'我'

时间:2018-04-17 09:53:06

标签: scala

在以下代码中,我可以将id定义为List[I]

abstract trait Repository[I,M] {

    def getOneById(id: List[I]): Option[M]
}

但为什么我不能在以下代码中将id定义为List[I]

abstract trait Repository[List[I],M] {

    def getOneById(id: List[I]): Option[M] //I get compiler error - cannot resolve I. Why?
}

2 个答案:

答案 0 :(得分:9)

abstract trait Repository[List[I],M] {
    def getOneById(id: List[I]): Option[M]
}

List类型参数的名称,与类型 scala.Predef.List无关。 I中的[List[I],M]仅表示此类型参数本身是接受单个类型参数的泛型类型。此名称I仅在List[I]内可见。

所以这可以同样改写为

abstract trait Repository[F[_],M] {
    def getOneById(id: F[I]): Option[M]
}

应该明确为什么这不会编译。

答案 1 :(得分:1)

[_greetButton setTitle:@"New title" forState:UIControlStateNormal];

应该有效。基本上在特征定义中,您只列出您的类型参数,而在id的右侧则需要指定类型。 abstract trait Repository[I,M] { def getOneById(id: List[I]): Option[M] } 是一个类型构造函数,在您的案例List

中接受一个参数

编辑:参见评论链