【问题标题】:IntelliJ shows type mismatch errors about dependent method types, even though sbt compiles fine (scala)IntelliJ 显示有关依赖方法类型的类型不匹配错误,即使 sbt 编译良好(scala)
【发布时间】:2021-04-23 22:40:27
【问题描述】:

我有如下特点:

trait NumberRepository[C <: AppContext] {
  def findAll(implicit ctx: C): ctx.Result[Seq[Int]]
  def findEvens(implicit ctx: C): ctx.Result[Seq[Int]] = findAll.map(_.filter(_ % 2 == 0))
}

当我使用 SBT 时,它可以毫无错误地编译。但是我的 IntelliJ 在其编辑器上报告了关于 findEvens 的返回值的类型不匹配错误。

Type mismatch.
Required: ctx.Result[scala.Seq[Int]]
Found: C#Result[scala.collection.Seq[Int]]

我发现我可以通过将 'ctx' 参数显式传递给 findAll 来解决此问题。但出于某些原因,我不想这样做。

// it's OK!
def findEvens(implicit ctx: C): ctx.Result[Seq[Int]] = findAll(ctx).map(_.filter(_ % 2 == 0))

这是一个错误吗?还是我的代码或配置有问题?有没有办法解决这个错误?

AppContext 如下:

trait AppContext {
  type Result[+A] <: AppResult[Result, A]
  def success[A](a: A): Result[A]
}

trait AppResult[F[+_], +A] {
  def map[B](f: A => B): F[B]
  def flatMap[B](f: A => F[B]): F[B]
}

class AppContextImpl extends AppContext {
  type Result[+A] = AppResultImpl[A]
  override def success[A](a: A): AppResultImpl[A] = AppResultImpl(Some(a))
}

case class AppResultImpl[+A](value: Option[A]) extends AppResult[AppResultImpl, A] {
  override def map[B](f: A => B): AppResultImpl[B] = AppResultImpl(value.map(f))
  override def flatMap[B](f: A => AppResultImpl[B]): AppResultImpl[B] = value match {
    case Some(a) => f(a)
    case None => AppResultImpl(None)
  }
}

class NumberRepositoryImpl extends NumberRepository[AppContextImpl] {
  override def findAll(implicit ctx: AppContextImpl): AppResultImpl[Seq[Int]] = ctx.success(1 to 10)
}

【问题讨论】:

    标签: scala intellij-idea dependent-method-type


    【解决方案1】:

    Scala type-aware highlighting 是一个独立于 Scala 编译器的 IntelliJ 功能,因此有时它的行为可能会有所不同。可能会报告错误的错误

    为了帮助我们修复突出显示的故障,您可以将其报告给 YouTrack 像往常一样或在错误的突出显示时按 Alt+Enter:

    还可以通过右下角的小 T 图标禁用/启用类型感知突出显示

    或者尝试从 BSP 获取错误诊断信息,这应该是 100% 真实的,但可能功能较少。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-30
    • 2019-03-27
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    相关资源
    最近更新 更多