Scala 3.5.0 unreachable case which was working with 3.4.2

I’m using Scala 3.5.0 with these compiler options:

    -language:strictEquality
    -Yexplicit-nulls
    -Wsafe-init
    -explain
    -indent
    -new-syntax
    -Xfatal-warnings
    -Wunused:all
    -Wvalue-discard
    -Wnonunit-statement
    -Xcheck-macros
    -source future

The following code gives a (fatal) warning about case _ => being unreachable:

import javax.swing.event.TreeSelectionEvent
import javax.swing.tree.TreePath

class testingCode:
  def process(t: TreeSelectionEvent) =
    val n = t.getNewLeadSelectionPath
    n match
      case tp: TreePath =>
      case _ =>

If I change n match with (n: TreePath | Null) match everything works fine. I’m convinced this wasn’t happening with Scala 3.4.2 (I don’t know about 3.4.3) and in any case if I refer to Explicit Nulls I can’t understand why it complains about an unreachable case. If I open TreeSelectionEvent.java it’s clear that n can be Null.

Unless this is a Scala bug I don’t understand why it’s happening and would love some insight.

1 Like

There was 1 major change related to Explicit Nulls when working with Java libraries, that might not have been documented well.

You can check how it behaves with the -Yno-flexible-types flag.

Thank you very much @WojciechMazur, I added the suggested flag and now everything works as it used to with 3.4.2.
I also had to put back a few .nn usages as expected.

I erroneously thought that flexible types are what I wanted, after reading more carefully the Explicit Nulls page I understand that’s not the case.

Thanks again!

Flexible types give users choices to use a value as nullable or non-nullable.

I think we should produce a better warning here, similar to without explicit nulls:
Unreachable case except for null (if this is intentional, consider writing case null => instead).

In this case, if a value is expected to be nullable, you should give a nullable type annotation to n.

I have created an issue for this: Better warning for matching values with flexible types in explicit nulls · Issue #21577 · scala/scala3 · GitHub