unsafeNulls features does not work, How?

Explicit Nulls is enalbed by -Yexplicit-nulls flag. For the following code:

import scala.language.unsafeNulls

def test(x: Int) = new Ordered[Int]:
       override def compare(y: Int): Int = x - y

The compiler error message:

object creation impossible, since def compareTo(x$0: T | Null): Int in trait Comparable in package java.lang is not defined 
(Note that
 parameter T | Null in def compareTo(x$0: T | Null): Int in trait Comparable in package java.lang does not match
 parameter Int in def compareTo(that: A): Int in trait Ordered in package scala.math

How to solve it with explicit nulls enabled?

Thanks for your help!

Scala 3.2.0 here


Probably the “relaxed” override check is not triggered in this situation where there’s both the null-riddled #compareTo() variant from java.lang.Comparable and the “pure” override in scala.math.Ordered…? May be a bug, not sure, but certainly an inconsistency - it looks like you can work around this, e.g. this compiles (even without unsafeNulls):

def test(x: Int): Ordered[Int] = (y: Int) => x - y

This is still kind of fishy, though - Comparable does allow null arguments, so this is likely going to be somewhat unsound whatever you do. The “proper solution” probably would be to not have Ordered inherit from Comparable in the first place…

As an aside, I’d almost always prefer a type class (Ordering) over an inheritance relationship (Ordered), anyway. This doesn’t immediately help this particular issue, as Ordering inherits from Comparator and thus suffers from the same problem. But it may make it easier to express and handle this incoherency in code, or just switch to alternatives - e.g. if you’re already using cats, there’s Order which doesn’t have the Comparator baggage.