繁体   English   中英

了解高级类型函数

[英]Understanding Higher Kinded Type Function

给定的ParentResult代数数据类型:

sealed trait Parent
case object Kid extends Parent

sealed trait Result[A <: Parent]
case class ResultImpl[A <: Parent](x: A) extends Result[A]

然后我写道:

def general[A <: Parent, F[_]](x: A, f: A => F[A]): F[A] = 
  f(x)

但是,我不确定如何调用general来获取ResultImpl[Kid.type]类型的输出。

我尝试过:

scala> general(Kid, ResultImpl.apply)
<console>:19: error: inferred kinds of the type arguments (Kid.type,ResultImpl) do not conform to the expected kinds of the type parameters (type A,type F).
ResultImpl's type parameters do not match type F's expected parameters:
type A's bounds <: Parent are stricter than type _'s declared bounds >: Nothing <: Any
       general(Kid, ResultImpl.apply)
       ^
<console>:19: error: type mismatch;
 found   : Kid.type
 required: A
       general(Kid, ResultImpl.apply)
               ^
<console>:19: error: type mismatch;
 found   : Nothing => ResultImpl[Nothing]
 required: A => F[A]
       general(Kid, ResultImpl.apply)
                               ^

我该如何使用general功能?

您还需要指定_<: Parent ,因为A是。 另外,您可能希望将参数分成两组,以便编译器正确推断A

def general[A <: Parent, F[_ <: Parent]](x: A)(f: A => F[A]): F[A] =
              f(x)

然后下一个按预期工作:

general(Kid)(ResultImpl(_))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM