bug icon indicating copy to clipboard operation
bug copied to clipboard

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

Open DaniRey opened this issue 3 years ago • 5 comments

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",

DaniRey avatar Sep 28 '22 08:09 DaniRey

You can reproduce without the for comprehension.

subTypeInstance match {
  case b: ArbitrarySubType => b
}

Jasper-M avatar Sep 28 '22 12:09 Jasper-M

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

DaniRey avatar Sep 28 '22 12:09 DaniRey

Is it possible to reproduce without involving an external dependency?

SethTisue avatar Sep 29 '22 22:09 SethTisue

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)
  }
}

Jasper-M avatar Sep 29 '22 22:09 Jasper-M

It's never just one dependency.

som-snytt avatar Sep 29 '22 23:09 som-snytt

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

unkarjedy avatar May 28 '24 16:05 unkarjedy