Skip to content

Pattern matching not match union types #8709

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
yankun1992 opened this issue Apr 12, 2020 · 4 comments
Closed

Pattern matching not match union types #8709

yankun1992 opened this issue Apr 12, 2020 · 4 comments

Comments

@yankun1992
Copy link

Minimized code

when using pattern match in union type like :

val buffer: List[String | Int | Long | Char] = List("string", 1, 2l, 'p', 3l, "sss", 2)
buffer.foreach { a =>
      a match {
        case _: String | Char => println(s"$a is ")
        case _ => println(s"$a is not ")
      }
    }

the char p is not match String | Char

Output

string is 
1 is not 
2 is not 
p is not 
3 is not 
sss is 
2 is not 

But if I put a bracket around the type:

buffer.foreach { a =>
      a match {
        case _: (String | Char) => println(s"$a is ")
        case _ => println(s"$a is not ")
      }
    }

the output is right

string is 
1 is not 
2 is not 
p is 
3 is not 
sss is 
2 is not 
@yankun1992
Copy link
Author

The dotty version is 0.23.0-RC1.

@SethTisue
Copy link
Member

note that case _: String | Char means "is a string, or is the scala.Char companion object"

Starting dotty REPL...
scala> (Char: Any) match { case _: String | Char => "yup" }                                         
val res0: String = yup

@smarter
Copy link
Member

smarter commented Apr 12, 2020

Yep, it's unfortunate but you have to write case _: (String | Char) as mentioned in http://dotty.epfl.ch/docs/reference/new-types/union-types-spec.html. No one has found a satisfying way around that (previous discussion: https://contributors.scala-lang.org/t/pre-sip-allow-in-pattern-alternatives/3043)

@smarter smarter closed this as completed Apr 12, 2020
@smarter
Copy link
Member

smarter commented Apr 12, 2020

... on the other hand, we should emit a warning in this case since it's clear that the object Char is not reachable since the scrutinee type is String | Int | Long | Char. I've opened an issue to keep track of that: #8711

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants