具有较高结合类型的特征

时间:2015-04-06 14:04:46

标签: scala

鉴于以下trait(来自此有用的shapeless talk):

scala> trait NatT[F[_], G[_]] { def apply[T](f: F[T]): G[T] }
warning: there were two feature warnings; re-run with -feature for details
defined trait NatT

我认为这意味着NatT接受两个更高级别的参数:FG

通过这个假设,我尝试创建一个F和G类型为Option的实例:

scala> case object Maybe extends NatT[Option, Option] {
     |   override def apply(f: Option[Int]) = f
     | }
<console>:8: error: object creation impossible, since method apply in trait NatT of type [T](f: Option[T])Option[T] is not de
fined
       case object Maybe extends NatT[Option, Option] {
                   ^
<console>:9: error: method apply overrides nothing.
Note: the super classes of object Maybe contain the following, non final members named apply:
def apply[T](f: Option[T]): Option[T]
         override def apply(f: Option[Int]) = f
                      ^

如何修复此Maybe实例的尝试?

1 个答案:

答案 0 :(得分:6)

您的apply方法缺少type参数。就这么简单。

case object Maybe extends NatT[Option, Option] {
    def apply[A](f: Option[A]): Option[A] = f
}

您在没有类型参数的情况下定义apply的尝试被视为一种不同的方法,因此apply似乎未实现。鉴于FG应该是更高级的,尝试将它们修复为Option[Int]并没有意义。