Scala类型参数与边界问题:Test[Option]编译失败原因排查
Scala泛型类型错误排查:Type argument Option does not have the same kind as its bound
你的代码:
import scala.concurrent.Future trait MyTrait[F[_]] { case class Test[X[_]](x: X[Int]) def test[G[_]]: F[Test[G]] } class LocImpl extends MyTrait[Future] { import scala.concurrent.ExecutionContext.Implicits.global def test[Option]: Future[Test[Option]] = { Future { new Test[Option](Option(1)) } } }
编译错误:
Type argument Option does not have the same kind as its bound [_$2]
问题原因:
你在实现test方法时,把泛型参数写成了[Option]——这相当于自定义了一个叫Option的普通类型参数,而非使用Scala标准库自带的Option类型构造器。
原trait里的test方法要求泛型参数G是一个类型构造器(也就是能接受一个类型参数的类型,比如Option、List这种,kind为* -> *),但你定义的[Option]是普通类型参数(kind为*),和方法要求的类型kind不匹配,所以编译器报错。
修复方案:
如果你的目的是固定返回Test[Option],直接去掉方法上的泛型参数,把方法签名改成这样:
def test: Future[Test[Option]] = { Future { new Test[Option](Option(1)) } }
如果想保留方法的泛型能力(支持任意类型构造器G[_]),则要正确声明泛型的kind,实现如下:
def test[G[_]]: Future[Test[G]] = { Future { new Test[Option](Option(1)) } }
内容的提问来源于stack exchange,提问作者joesan
相关产品推荐
相关产品推荐

