Skip to content

Commit 4b9c698

Browse files
committed
Don't null out private field in trait
1 parent 5491717 commit 4b9c698

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

compiler/src/dotty/tools/dotc/transform/CollectNullableFields.scala

+6-2
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,12 @@ object CollectNullableFields {
3333
* initialised.
3434
*
3535
* A field is nullable if all the conditions below hold:
36+
* - belongs to a non trait-class
3637
* - is private
3738
* - is not lazy
3839
* - its type is nullable, or is an expression type (e.g. => Int)
3940
* - is on used in a lazy val initializer
4041
* - defined in the same class as the lazy val
41-
* - TODO from Scalac? from a non-trait class
4242
*/
4343
class CollectNullableFields extends MiniPhase {
4444
import tpd._
@@ -63,7 +63,11 @@ class CollectNullableFields extends MiniPhase {
6363
def isNullableType(tpe: Type) =
6464
tpe.isInstanceOf[ExprType] ||
6565
tpe.widenDealias.typeSymbol.isNullableClass
66-
val isNullablePrivateField = sym.isField && sym.is(Private, butNot = Lazy) && isNullableType(sym.info)
66+
val isNullablePrivateField =
67+
sym.isField &&
68+
sym.is(Private, butNot = Lazy) &&
69+
!sym.owner.is(Trait) &&
70+
isNullableType(sym.info)
6771

6872
if (isNullablePrivateField)
6973
nullability.get(sym) match {

tests/run/i1692.scala

+9
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ class LazyNotNullable {
4949
}
5050
}
5151

52+
trait LazyTrait {
53+
private val a = "A"
54+
lazy val l0 = a
55+
}
56+
5257
object Test {
5358
def main(args: Array[String]): Unit = {
5459
nullableTests()
@@ -111,6 +116,10 @@ object Test {
111116
val inner = new lz.Inner
112117
assert(inner.l8 == "H")
113118
assertNotNull("h")
119+
120+
val fromTrait = new LazyTrait {}
121+
assert(fromTrait.l0 == "A")
122+
assert(readField("LazyTrait$$a", fromTrait) != null) // fragile: test will break if compiler generated name change
114123
}
115124

116125
def readField(fieldName: String, target: Any): Any = {

0 commit comments

Comments
 (0)