scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
230 stars 21 forks source link

Unexpected "scrutinee is incompatible with pattern type" in for-comprehension #12656

Open DaniRey opened 1 year ago

DaniRey commented 1 year ago

The following code

import zio.prelude.Subtype

object PreludeForComprehensionIssue extends App {
  object ArbitrarySubType extends Subtype[String]
  type ArbitrarySubType = ArbitrarySubType.Type

  val subTypeInstance: ArbitrarySubType = ArbitrarySubType("I am the sub type instance")

  val result = for {
    _ <- Some("A")
    b: ArbitrarySubType <- Some(subTypeInstance)
  } yield b

  println(result)
}

produces the error

scrutinee is incompatible with pattern type;
 found   : PreludeForComprehensionIssue.ArbitrarySubType
    (which expands to)  PreludeForComprehensionIssue.ArbitrarySubType.Type
 required: String

in Scala 2.13.9. It compiles without issues in Scala 3.2.0. It can also be compiled without issues by adding better-monadic-for https://github.com/oleg-py/better-monadic-for

It can be tried via https://scastie.scala-lang.org/nYj3MNfXQFGE62TaQK7G5A The only required dependency is "dev.zio" %% "zio-prelude" % "1.0.0-RC16",

Jasper-M commented 1 year ago

You can reproduce without the for comprehension.

subTypeInstance match {
  case b: ArbitrarySubType => b
}
DaniRey commented 1 year ago

Great finding @Jasper-M

It again compiles in Scala 3.2.0, but doesn't with Scala 2.13.9 It can be tried via https://scastie.scala-lang.org/8i41SfWcRzmCaqY6W00mRw

SethTisue commented 1 year ago

Is it possible to reproduce without involving an external dependency?

Jasper-M commented 1 year ago

This should do the trick https://scastie.scala-lang.org/dWyBGp5SR3a9lrUm1v0ldQ

trait Subtype[A] {
  type Type <: A
  def apply(a: A): Type = a.asInstanceOf[Type]
}

object PreludeForComprehensionIssue extends App {
  object ArbitrarySubType extends Subtype[String]
  type ArbitrarySubType = ArbitrarySubType.Type

  val subTypeInstance: ArbitrarySubType = ArbitrarySubType("I am the sub type instance")

  subTypeInstance match {
    case b: ArbitrarySubType => println(b)
  }
}
unkarjedy commented 3 months ago

JFTR, the related ticket in IntelliJ: https://youtrack.jetbrains.com/issue/SCL-20607/Scala-Plugin-falsely-reports-compilation-error Inn Scala Plugin we show the error for Scala as well