scala - 多态方法适用于 lambda 类型,但不适用于 Scala 3 中的类型通配符

标签 scala scala-3 higher-kinded-types kind-projector

在 Scala 3 中,我可以使用 lambda 类型为状态定义仿函数:

  given stateFunctor[S]: Functor[[A] =>> State[S, A]] with
    override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })

我希望它能与 ?_ 通配符一起使用:

  given stateFunctor[S]: Functor[State[S, ?]] with
    override def map[A, B](a: State[S, A])(fx: A => B): State[S, B] = State(a.run.andThen { case (s, a) => (s, fx(a)) })

但我收到以下编译错误:

Type argument domain.State[S, ? <: AnyKind] does not have the same kind as its bound [_$1] given stateFunctor[S]: Functor[State[S, ? <: AnyKind]] with

为什么不起作用?我缺少什么?我认为 Scala 3 支持类型通配符的种类投影语法。

Scala 版本:3.1.3

如果您需要它,这里是StateFunctor定义:

case class State[S, A](run:S => (S, A)):
  def exec(s:S):S = run(s)._1
  def eval(s:S):A = run(s)._2
trait Functor[F[_]]:
  def map[A, B](a: F[A])(fx: A => B): F[B]

最佳答案

? 错误。 ? 用于存在类型 State[S, ?] (在 Scala 2 中是 State[S, _] 又名 State[ S, A] forSome { type A }),不适用于 lambda 类型。

_ 代表 lambda 类型(在 Scala 2 中,它们被模拟 ({ type F[A] = State[S, A] })#F)。所以它应该是 State[S, _] 但这尚未实现。

https://docs.scala-lang.org/scala3/reference/changed-features/wildcards.html

The syntax of wildcard arguments in types has changed from _ to ?

We would like to use the underscore syntax _ to stand for an anonymous type parameter, aligning it with its meaning in value parameter lists. So, just as f(_) is a shorthand for the lambda x => f(x), in the future C[_] will be a shorthand for the type lambda [X] =>> C[X].

到目前为止,您可以编写 [A] =>> State[S, A] 或使用 kind projector 状态[S,*]

scalaVersion := "3.2.1"

scalacOptions += "-Ykind-projector"

关于scala - 多态方法适用于 lambda 类型,但不适用于 Scala 3 中的类型通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74267610/

相关文章:

scala - Scala 的类型删除如何用于更高种类的类型参数?

scala - 在 intellij idea HttpServletResponse 中运行 spark - ClassNotFoundException

scala - 如何确保内联类型匹配(scala 3)中的两个参数引用相同的类型

scala - 模式匹配更高种类的参数

scala - 在 Scala 3 中是否可以通过泛型类型进行模式匹配?

Scala 3 - 使用产品进行泛型编程

具有更高种类类型和方差的 scala 类型类

scala - flatten函数中使用的模式匹配中List[_]的解释

java - 如何防止 IntelliJ 在每次 Gradle 构建后要求提供 Scala SDK?

scala - 为什么 Numeric 对待一元和二进制的方式不同?