Skip to content

Commit 9dd0968

Browse files
authored
Merge pull request scala#13337 from dotty-staging/unsafenulls-java-call
Strip Nulls from Java members when unsafeNulls is enabled
2 parents a11fdef + 9b9a969 commit 9dd0968

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3762,6 +3762,15 @@ class Typer extends Namer
37623762
if target <:< pt then
37633763
return readapt(tree.cast(target))
37643764

3765+
// if unsafeNulls is enabled, try to strip nulls from Java function calls
3766+
if Nullables.unsafeNullsEnabled then
3767+
tree match
3768+
case _: Apply | _: Select if tree.symbol.is(JavaDefined) =>
3769+
wtp match
3770+
case OrNull(wtp1) => return readapt(tree.cast(wtp1))
3771+
case _ =>
3772+
case _ =>
3773+
37653774
def recover(failure: SearchFailureType) =
37663775
if canDefineFurther(wtp) || canDefineFurther(pt) then readapt(tree)
37673776
else err.typeMismatch(tree, pt, failure)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
public class J {
2+
public String f1() {
3+
return "";
4+
}
5+
6+
public int f2() {
7+
return 0;
8+
}
9+
10+
public <T> T g1() {
11+
return null;
12+
}
13+
}
14+
15+
class J2<T> {
16+
public T x = null;
17+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Check Java calls have been cast to non-nullable.
2+
3+
val j: J = new J
4+
5+
val s1: String = j.f1() // error
6+
7+
val s1n: String | Null = j.f1()
8+
9+
val i1: Int = j.f2()
10+
11+
val s2: String = j.g1[String]() // error
12+
13+
val s2n: String | Null = j.g1[String]()
14+
15+
val s3: String = j.g1[String | Null]() // error
16+
17+
val s3n: String | Null = j.g1[String | Null]()
18+
19+
val i2: Int = j.g1[Int]() // error
20+
21+
val a1: Any = j.g1[Any]()
22+
23+
val ar1: AnyRef = j.g1[AnyRef]() // error
24+
25+
val n1: Null = j.g1[Null]()
26+
27+
val ar2: AnyRef = j.g1[Null]() // error
28+
29+
def clo1[T]: T = j.g1[T]() // error
30+
31+
def clo2[T <: AnyRef]: T = j.g1[T | Null]() // error
32+
33+
def clo3[T >: Null <: AnyRef | Null]: T = j.g1[T]()
34+
35+
def testJ2[T]: T =
36+
val j2: J2[T] = new J2
37+
j2.x // error

0 commit comments

Comments
 (0)