Skip to content

warn for new Array[T] when T is not nullable #15763

Open
@olhotak

Description

@olhotak

With explicit nulls, one source of unsoundness is array creation using new Array - the array is filled with nulls even if the element type is not nullable. This has been an observed cause of several nullness bugs in the compiler. The latest of these is #15687 fixed by #15748.

At one time we planned to deprecate the raw new Array and prefer library functions: Array.fill and Array.apply for arrays with a non-nullable element type that are guaranteed to be initialized and a new Array.ofNulls function to create nullable arrays, with signature Array.ofNulls[T](size: Int): Array[T|Null].

A simpler solution would be for the compiler to issue a warning for every new Array[T] when T is not a supertype of Null.

A question is whether this should be considered an explicit nulls warning or an initialization warning. That is, should it be issued only with both -Ysafe-init and -Yexplicit-nulls, or even without -Ysafe-init. On one hand, it doesn't really fit with the initialization checker implementation, and more with the checks done for explicit nulls (e.g. in RefChecks). On the other hand, from the point of view of users, there is more precedent for -Ysafe-init to issue warnings, while -Yexplicit-nulls usually changes types, possibly leading to compilation errors. It's debatable whether having an Array[String] full of nulls is a failure to initialize or an incorrect type.

/cc @noti0na1 @liufengyun

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions