【问题标题】:Why does Option[Try[_]] not conform to F[_]?为什么 Option[Try[_]] 不符合 F[_]?
【发布时间】:2019-12-27 12:25:20
【问题描述】:

所以有这样的东西:

@ trait IntWrapper[F[_]] { def apply(i: Int): F[Int] }
defined trait IntWrapper

@ class OptWrapper extends IntWrapper[Option] { def apply(i: Int) = Option(i) }
defined class OptWrapper

我现在想做这样的事情:

@ class TryOptWrapper extends IntWrapper[Try[Option]] { def apply(i: Int) = Try(Option(i)) }
cmd19.sc:1: scala.util.Try[Option] takes no type parameters, expected: one
class TryOptWrapper extends IntWrapper[Try[Option]] { def apply(i: Int) = Try(Option(i)) }
                                       ^
Compilation Failed

(如果我将特征扩展声明为class TryOptWrapper extends IntWrapper[Try[Option[_]]],也是一样)

现在,也许最有趣的是,这行得通:

@ type Topt[T] = Try[Option[T]]

@ class ToptWrapper extends IntWrapper[Topt] { def apply(i: Int) = Try(Option(i)) }
defined class ToptWrapper

现在,是否可以做同样的事情——即实现一个类型参数为 nested 参数化类型的特征——而不必显式声明类型别名?确实感觉我在这里遗漏了一些语法。

【问题讨论】:

    标签: scala types higher-kinded-types type-kinds kind-projector


    【解决方案1】:

    Try 期望类型参数 *Option 有类型 * => * 所以你不能写 Try[Option],只能写 Try[Option[Int]], Try[Option[String]], Try[Option[_]]...

    尝试输入 lambda

    class TryOptWrapper extends IntWrapper[({ type λ[A] = Try[Option[A]] })#λ] { def apply(i: Int) = Try(Option(i)) }
    

    或者kind-projector

    class TryOptWrapper extends IntWrapper[Lambda[A => Try[Option[A]]]] { def apply(i: Int) = Try(Option(i)) }
    

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 2018-09-10
      • 1970-01-01
      • 2015-08-10
      • 2019-10-22
      • 2021-06-05
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      相关资源
      最近更新 更多