@@ -6,6 +6,7 @@ import io.*
66import classpath .AggregateClassPath
77import core .*
88import Symbols .* , Types .* , Contexts .* , StdNames .*
9+ import Phases .*
910import Flags .*
1011import transform .ExplicitOuter
1112
@@ -44,6 +45,17 @@ class JavaPlatform extends Platform {
4445
4546 def rootLoader (root : TermSymbol )(using Context ): SymbolLoader = new SymbolLoaders .PackageLoader (root, classPath)
4647
48+ private def samMethodHasCompatibleErasedSignature (cls : ClassSymbol )(using Context ): Boolean = atPhase(erasurePhase):
49+ cls.typeRef.possibleSamMethods.toList match
50+ case samDenot :: Nil =>
51+ val samMethod = samDenot.symbol
52+ val samErasedResult = TypeErasure .erasure(samMethod.info.resultType)
53+ samMethod.allOverriddenSymbols.forall { overridden =>
54+ val overriddenErasedResult = TypeErasure .erasure(overridden.info.resultType)
55+ samErasedResult =:= overriddenErasedResult
56+ }
57+ case _ => false // No SAM method or multiple - handled elsewhere
58+
4759 /** Is the SAMType `cls` also a SAM under the rules of the JVM? */
4860 def isSam (cls : ClassSymbol )(using Context ): Boolean =
4961 cls.isAllOf(NoInitsTrait ) &&
@@ -52,8 +64,10 @@ class JavaPlatform extends Platform {
5264 ! ExplicitOuter .needsOuterIfReferenced(cls) &&
5365 // Superaccessors already show up as abstract methods here, so no test necessary
5466 cls.typeRef.fields.isEmpty &&
55- // LambdaMetafactory can't handle SAMs with Unit return type unless it's a FunctionN itself
56- ! cls.typeRef.possibleSamMethods.exists(_.info.resultType.isRef(defn.UnitClass ))
67+ // Check that SAM method's erased signature is compatible with all overridden methods
68+ // For example, `void apply(Object)` is not compatible with `Object apply(Object)`
69+ // even though both can have the same type signature `def apply(o: Object): Unit` before erasure.
70+ samMethodHasCompatibleErasedSignature(cls)
5771
5872 /** We could get away with excluding BoxedBooleanClass for the
5973 * purpose of equality testing since it need not compare equal
0 commit comments