Skip to content

Commit 31e7f7c

Browse files
authored
Relax flow typing checks on Flexible Types (#24278)
These changes allow flow-typing to view flexible types as non-nullable at relevant places. ```scala //> using options -Yexplicit-nulls def main() = var result: String | Null = null result = "".trim() result.trim() ``` Without this PR, the access of trim on result will give an error. This pattern is used in community build projects like sconfig. After this change, calling .nn on a flexible type **directly** will still not give a warning, as intended. However, calling .nn on a variable that is previously flow typed to be a flexible type will now give a warning as a side effect of this change. We believe that the benefits of this change outweigh the drawback.
2 parents d221ef5 + 3f2b3e5 commit 31e7f7c

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

compiler/src/dotty/tools/dotc/core/NullOpsDecorator.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ object NullOpsDecorator:
4747

4848
/** Is self (after widening and dealiasing) a type of the form `T | Null`? */
4949
def isNullableUnion(using Context): Boolean = {
50-
val stripped = self.stripNull()
50+
val stripped = self.stripNull(stripFlexibleTypes = false)
5151
stripped ne self
5252
}
5353
end extension
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// This test is based on sconfig/sconfig/shared/src/main/scala/org/ekrich/config/impl/SimpleConfig.scala
2+
// In cases where a nullable variable is assigned a flexible type, we want
3+
// later code to type the variable access as non-nullable
4+
// Added in https://github.com/scala/scala3/pull/24278
5+
6+
def main() =
7+
var result: String | Null = null
8+
result = "".trim()
9+
result.trim()

0 commit comments

Comments
 (0)