E216: Unnecessary .nn

This warning is emitted when the .nn (not null) method is used unnecessarily. This warning only appears when explicit nulls are enabled with the -Yexplicit-nulls compiler flag.

The .nn method is used to assert that a nullable value is not null, converting T | Null to T. However, it is unnecessary in two cases:

  1. Qualifier is already not null: When the value is already of a non-nullable type, calling .nn has no effect.
  2. Expected type admits null: When the expected type already accepts null values, asserting non-nullability is pointless.

Example

When the qualifier is already not null:

//> using options -Yexplicit-nulls

def example: String =
  val s: String = "hello"
  s.nn

Error

-- [E216] Syntax Warning: example.scala:5:4 ------------------------------------
5 |  s.nn
  |  ^^^^
  |  Unnecessary .nn: qualifier is already not null

Solution

Remove the unnecessary .nn call:

//> using options -Yexplicit-nulls

def example: String =
  val s: String = "hello"
  s

When the expected type admits null, only use .nn if you need to narrow the type for subsequent operations:

//> using options -Yexplicit-nulls

def example: String =
  val s: String | Null = getSomeValue()
  s.nn  // necessary to convert String | Null to String

def getSomeValue(): String | Null = "value"