Unexpected "scrutinee is incompatible with pattern type" in for-comprehension
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",
You can reproduce without the for comprehension.
subTypeInstance match {
case b: ArbitrarySubType => b
}
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
Is it possible to reproduce without involving an external dependency?
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)
}
}
It's never just one dependency.
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