Skip to content

Commit

Permalink
fix: non-null to non-nullable types (#3782)
Browse files Browse the repository at this point in the history
  • Loading branch information
danil-pavlov authored Sep 11, 2023
1 parent 6650e67 commit b3026ad
Show file tree
Hide file tree
Showing 20 changed files with 40 additions and 39 deletions.
2 changes: 1 addition & 1 deletion docs/topics/collection-elements.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ It combines 2 actions:
- Maps the collection with the selector function
- Returns the first non-null value in the result

`firstNotNullOf()` throws the `NoSuchElementException` if the resulting collection doesn't have a non-null element.
`firstNotNullOf()` throws the `NoSuchElementException` if the resulting collection doesn't have a non-nullable element.
Use the counterpart [`firstNotNullOfOrNull()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/first-not-null-of-or-null.html)
to return null in this case.

Expand Down
4 changes: 2 additions & 2 deletions docs/topics/collection-filtering.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ There are also functions that narrow the element type by filtering elements of a
{kotlin-runnable="true" kotlin-min-compiler-version="1.3"}

* [`filterNotNull()`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-not-null.html) returns all
non-null elements. Being called on a `List<T?>`, `filterNotNull()` returns a `List<T: Any>`, thus allowing you to treat
the elements as non-null objects.
non-nullable elements. Being called on a `List<T?>`, `filterNotNull()` returns a `List<T: Any>`, thus allowing you to treat
the elements as non-nullable objects.

```kotlin
fun main() {
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/competitive-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ Note the use of Kotlin's
[null-assertion operator](null-safety.md#the-operator) `!!`
after the [readLine()](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/read-line.html) function call.
Kotlin's `readLine()` function is defined to return a
[nullable type](null-safety.md#nullable-types-and-non-null-types)
[nullable type](null-safety.md#nullable-types-and-non-nullable-types)
`String?` and returns `null` on the end of the input, which explicitly forces the developer to handle the
case of missing input.

Expand Down
2 changes: 1 addition & 1 deletion docs/topics/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ You can call `toString()` in Kotlin without checking for `null`, as the check al
```kotlin
fun Any?.toString(): String {
if (this == null) return "null"
// After the null check, 'this' is autocast to a non-null type, so the toString() below
// After the null check, 'this' is autocast to a non-nullable type, so the toString() below
// resolves to the member function of the Any class
return toString()
}
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/home.xml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<a href="coding-conventions.md" description="Recommendations on the code organization, formatting, and naming">Coding conventions</a>
<a href="basic-types.md" description="Kotlin type system: numbers, strings, arrays, and other built-in types">Basic types</a>
<a href="control-flow.md" description="Conditions and loops: if, when, for, while">Control flow</a>
<a href="null-safety.md" description="Nullable and non-null types, elvis operator, safe calls and casts ">Null safety</a>
<a href="null-safety.md" description="Nullable and non-nullable types, elvis operator, safe calls and casts ">Null safety</a>
<a href="coroutines-overview.md" description="Concurrency: coroutines, flows, channels">Coroutines</a>
</highlighted-group>
<custom-groups>
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/js/js-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,7 @@ in each `Video` object, so you can pass it as a prop and access its attributes.
}
```

2. Because the `VideoPlayerProps` interface specifies that the `VideoPlayer` component takes a non-null `Video`, make
2. Because the `VideoPlayerProps` interface specifies that the `VideoPlayer` component takes a non-nullable `Video`, make
sure to handle this in the `App` component accordingly.

In `App.kt`, replace the previous `div` snippet for the video player with the following:
Expand Down
16 changes: 8 additions & 8 deletions docs/topics/jvm/java-interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,14 @@ item.substring(1) // allowed, throws an exception if item == null

Platform types are *non-denotable*, meaning that you can't write them down explicitly in the language.
When a platform value is assigned to a Kotlin variable, you can rely on the type inference (the variable will have an inferred
platform type then, as `item` has in the example above), or you can choose the type you expect (both nullable and non-null types are allowed):
platform type then, as `item` has in the example above), or you can choose the type you expect (both nullable and non-nullable types are allowed):

```kotlin
val nullable: String? = item // allowed, always works
val notNull: String = item // allowed, may fail at runtime
```

If you choose a non-null type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-null variables from holding
If you choose a non-nullable type, the compiler will emit an assertion upon assignment. This prevents Kotlin's non-nullable variables from holding
nulls. Assertions are also emitted when you pass platform values to Kotlin functions expecting non-null values and in other cases.
Overall, the compiler does its best to prevent nulls from propagating far through the program although sometimes this is
impossible to eliminate entirely, because of generics.
Expand All @@ -195,7 +195,7 @@ so there is a mnemonic notation for them:

### Nullability annotations

Java types that have nullability annotations are represented not as platform types, but as actual nullable or non-null
Java types that have nullability annotations are represented not as platform types, but as actual nullable or non-nullable
Kotlin types. The compiler supports several flavors of nullability annotations, including:

* [JetBrains](https://www.jetbrains.com/idea/help/nullable-and-notnull-annotations.html)
Expand Down Expand Up @@ -320,7 +320,7 @@ nullability which deviates from the nullability annotations from Java.
The [`@Nonnull`](https://www.javadoc.io/doc/com.google.code.findbugs/jsr305/latest/javax/annotation/Nonnull.html) annotation defined
in [JSR-305](https://jcp.org/en/jsr/detail?id=305) is supported for denoting nullability of Java types.

If the `@Nonnull(when = ...)` value is `When.ALWAYS`, the annotated type is treated as non-null; `When.MAYBE` and
If the `@Nonnull(when = ...)` value is `When.ALWAYS`, the annotated type is treated as non-nullable; `When.MAYBE` and
`When.NEVER` denote a nullable type; and `When.UNKNOWN` forces the type to be [platform one](#null-safety-and-platform-types).

A library can be compiled against the JSR-305 annotations, but there's no need to make the annotations artifact (e.g. `jsr305.jar`)
Expand Down Expand Up @@ -406,7 +406,7 @@ interface A {
```

> The types in this example only take place with the strict mode enabled; otherwise, the platform types remain.
>See the [`@UnderMigration` annotation](#undermigration-annotation) and [Compiler configuration](#compiler-configuration) sections.
> See the [`@UnderMigration` annotation](#undermigration-annotation) and [Compiler configuration](#compiler-configuration) sections.
>
{type="note"}

Expand Down Expand Up @@ -441,14 +441,14 @@ A library maintainer can add `@UnderMigration` status to both type qualifier nic
public @interface NonNullApi {
}

// The types in the class are non-null, but only warnings are reported
// The types in the class are non-nullable, but only warnings are reported
// because `@NonNullApi` is annotated `@UnderMigration(status = MigrationStatus.WARN)`
@NonNullApi
public class Test {}
```

>The migration status of a nullability annotation is not inherited by its type qualifier nicknames but is applied
>to its usages in default type qualifiers.
> The migration status of a nullability annotation is not inherited by its type qualifier nicknames but is applied
> to its usages in default type qualifiers.
>
{type="note"}

Expand Down
2 changes: 1 addition & 1 deletion docs/topics/jvm/java-to-kotlin-interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ fun writeToFile() {

## Null-safety

When calling Kotlin functions from Java, nobody prevents us from passing `null` as a non-null parameter.
When calling Kotlin functions from Java, nobody prevents us from passing `null` as a non-nullable parameter.
That's why Kotlin generates runtime checks for all public functions that expect non-nulls.
This way we get a `NullPointerException` in the Java code immediately.

Expand Down
2 changes: 1 addition & 1 deletion docs/topics/jvm/java-to-kotlin-nullability-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ After the check is passed successfully, the compiler treats the variable as if i
in the scope where the compiler performs the check.

If you don't perform this check, the code will fail to compile with the following message:
"Only [safe (?.)](null-safety.md#safe-calls) or [non-null asserted (!!.) calls](null-safety.md#the-operator) are allowed
"Only [safe (?.)](null-safety.md#safe-calls) or [non-nullable asserted (!!.) calls](null-safety.md#the-operator) are allowed
on a [nullable receiver](extensions.md#nullable-receiver) of type String?".

You can write the same shorter – use the [safe-call operator ?. (If-not-null shorthand)](idioms.md#if-not-null-shorthand),
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/jvm/jvm-spring-boot-add-data-class.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ It requires changing the `MessageController` class to respond with a JSON docume
</p>
</def>
<def title="Nullable types – String?">
<p>Kotlin provides <a href="null-safety.md#nullable-types-and-non-null-types">built-in support for nullable types</a>. In Kotlin, the type system distinguishes between references that can hold <code>null</code> (<i>nullable references</i>) and those that cannot (<i>non-nullable references</i>).<br/>
<p>Kotlin provides <a href="null-safety.md#nullable-types-and-non-nullable-types">built-in support for nullable types</a>. In Kotlin, the type system distinguishes between references that can hold <code>null</code> (<i>nullable references</i>) and those that cannot (<i>non-nullable references</i>).<br/>
For example, a regular variable of type <code>String</code> cannot hold <code>null</code>. To allow nulls, you can declare a variable as a nullable string by writing <code>String?</code>.
</p>
<p>The <code>id</code> property of the <code>Message</code> class is declared as a nullable type this time.
Expand Down
8 changes: 4 additions & 4 deletions docs/topics/keyword-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ in other contexts:
* `inline` tells the compiler to [inline a function and the lambdas passed to it at the call site](inline-functions.md).
* `inner` allows referring to an outer class instance from a [nested class](nested-classes.md).
* `internal` marks a declaration as [visible in the current module](visibility-modifiers.md).
* `lateinit` allows initializing a [non-null property outside of a constructor](properties.md#late-initialized-properties-and-variables).
* `lateinit` allows initializing a [non-nullable property outside of a constructor](properties.md#late-initialized-properties-and-variables).
* `noinline` turns off [inlining of a lambda passed to an inline function](inline-functions.md#noinline).
* `open` allows [subclassing a class or overriding a member](classes.md#inheritance).
* `operator` marks a function as [overloading an operator or implementing a convention](operator-overloading.md).
Expand Down Expand Up @@ -143,13 +143,13 @@ Kotlin supports the following operators and special symbols:
* `===`, `!==` - [referential equality operators](equality.md#referential-equality).
* `<`, `>`, `<=`, `>=` - [comparison operators](operator-overloading.md#comparison-operators) (translated to calls of `compareTo()` for non-primitive types).
* `[`, `]` - [indexed access operator](operator-overloading.md#indexed-access-operator) (translated to calls of `get` and `set`).
* `!!` [asserts that an expression is non-null](null-safety.md#the-operator).
* `?.` performs a [safe call](null-safety.md#safe-calls) (calls a method or accesses a property if the receiver is non-null).
* `!!` [asserts that an expression is non-nullable](null-safety.md#the-operator).
* `?.` performs a [safe call](null-safety.md#safe-calls) (calls a method or accesses a property if the receiver is non-nullable).
* `?:` takes the right-hand value if the left-hand value is null (the [elvis operator](null-safety.md#elvis-operator)).
* `::` creates a [member reference](reflection.md#function-references) or a [class reference](reflection.md#class-references).
* `..`, `..<` create [ranges](ranges.md).
* `:` separates a name from a type in a declaration.
* `?` marks a type as [nullable](null-safety.md#nullable-types-and-non-null-types).
* `?` marks a type as [nullable](null-safety.md#nullable-types-and-non-nullable-types).
* `->`
- separates the parameters and body of a [lambda expression](lambdas.md#lambda-expression-syntax).
- separates the parameters and return type declaration in a [function type](lambdas.md#function-types).
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/lambdas.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ These types have a special notation that corresponds to the signatures of the fu
The function type notation can optionally include names for the function parameters: `(x: Int, y: Int) -> Point`.
These names can be used for documenting the meaning of the parameters.

To specify that a function type is [nullable](null-safety.md#nullable-types-and-non-null-types), use parentheses as follows:
To specify that a function type is [nullable](null-safety.md#nullable-types-and-non-nullable-types), use parentheses as follows:
`((Int, Int) -> Int)?`.

Function types can also be combined using parentheses: `(Int) -> ((Int) -> Unit)`.
Expand Down
8 changes: 4 additions & 4 deletions docs/topics/native/native-objc-interop.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ class Sample<T>() {

In order to support a potentially nullable type, the Objective-C header needs to define `myVal` with a nullable return value.

To mitigate this, when defining your generic classes, if the generic type should *never* be null, provide a non-null
To mitigate this, when defining your generic classes, if the generic type should _never_ be null, provide a non-nullable
type constraint:

```kotlin
Expand All @@ -411,7 +411,7 @@ class Sample<T : Any>() {
}
```

That will force the Objective-C header to mark `myVal` as non-null.
That will force the Objective-C header to mark `myVal` as non-nullable.

#### Variance

Expand All @@ -431,8 +431,8 @@ let variOutAny : GenVarOut<BaseData> = variOut as! GenVarOut<BaseData>
#### Constraints

In Kotlin, you can provide upper bounds for a generic type. Objective-C also supports this, but that support is unavailable
in more complex cases, and is currently not supported in the Kotlin - Objective-C interop. The exception here being a non-null
upper bound will make Objective-C methods/properties non-null.
in more complex cases, and is currently not supported in the Kotlin - Objective-C interop. The exception here being a non-nullable
upper bound will make Objective-C methods/properties non-nullable.

#### To disable

Expand Down
10 changes: 5 additions & 5 deletions docs/topics/null-safety.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[//]: # (title: Null safety)

## Nullable types and non-null types
## Nullable types and non-nullable types

Kotlin's type system is aimed at eliminating the danger of null references, also known as [The Billion Dollar Mistake](https://en.wikipedia.org/wiki/Null_pointer#History).

Expand All @@ -23,13 +23,13 @@ The only possible causes of an NPE in Kotlin are:
* Other issues caused by external Java code.

In Kotlin, the type system distinguishes between references that can hold `null` (nullable references) and those that
cannot (non-null references).
cannot (non-nullable references).
For example, a regular variable of type `String` cannot hold `null`:

```kotlin
fun main() {
//sampleStart
var a: String = "abc" // Regular initialization means non-null by default
var a: String = "abc" // Regular initialization means non-nullable by default
a = null // compilation error
//sampleEnd
}
Expand Down Expand Up @@ -196,7 +196,7 @@ fun foo(node: Node): String? {

## The `!!` operator

The third option is for NPE-lovers: the not-null assertion operator (`!!`) converts any value to a non-null
The third option is for NPE-lovers: the not-null assertion operator (`!!`) converts any value to a non-nullable
type and throws an exception if the value is `null`. You can write `b!!`, and this will return a non-null value of `b`
(for example, a `String` in our example) or throw an NPE if `b` is `null`:

Expand All @@ -217,7 +217,7 @@ val aInt: Int? = a as? Int

## Collections of a nullable type

If you have a collection of elements of a nullable type and want to filter non-null elements, you can do so by using
If you have a collection of elements of a nullable type and want to filter non-nullable elements, you can do so by using
`filterNotNull`:

```kotlin
Expand Down
1 change: 1 addition & 0 deletions docs/topics/operator-overloading.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ The `==` operation is special: it is translated to a complex expression that scr
All comparisons are translated into calls to `compareTo`, that is required to return `Int`.

### Property delegation operators

`provideDelegate`, `getValue` and `setValue` operator functions are described
in [Delegated properties](delegated-properties.md).

Expand Down
6 changes: 3 additions & 3 deletions docs/topics/properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated"

## Late-initialized properties and variables

Normally, properties declared as having a non-null type must be initialized in the constructor.
Normally, properties declared as having a non-nullable type must be initialized in the constructor.
However, it is often the case that doing so is not convenient. For example, properties can be initialized through dependency
injection, or in the setup method of a unit test. In these cases, you cannot supply a non-null initializer in the constructor,
injection, or in the setup method of a unit test. In these cases, you cannot supply a non-nullable initializer in the constructor,
but you still want to avoid null checks when referencing the property inside the body of a class.

To handle such cases, you can mark the property with the `lateinit` modifier:
Expand All @@ -190,7 +190,7 @@ public class MyTest {

This modifier can be used on `var` properties declared inside the body of a class (not in the primary constructor,
and only when the property does not have a custom getter or setter), as well as for top-level properties and local variables.
The type of the property or variable must be non-null, and it must not be a primitive type.
The type of the property or variable must be non-nullable, and it must not be a primitive type.

Accessing a `lateinit` property before it has been initialized throws a special exception that clearly identifies the property
being accessed and the fact that it hasn't been initialized.
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/scope-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Detailed information about these functions is provided in the dedicated sections

Here is a short guide for choosing scope functions depending on the intended purpose:

* Executing a lambda on non-null objects: `let`
* Executing a lambda on non-nullable objects: `let`
* Introducing an expression as a variable in local scope: `let`
* Object configuration: `apply`
* Object configuration and computing the result: `run`
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/tour/kotlin-tour-null-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ fun main() {
nullable = null

// By default, null values aren't accepted
var inferredNonNull = "The compiler assumes non-null"
var inferredNonNull = "The compiler assumes non-nullable"

// Throws a compiler error
inferredNonNull = null
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/typecasts.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,4 @@ To avoid exceptions, use the *safe* cast operator `as?`, which returns `null` on
val x: String? = y as? String
```

Note that despite the fact that the right-hand side of `as?` is a non-null type `String`, the result of the cast is nullable.
Note that despite the fact that the right-hand side of `as?` is a non-nullable type `String`, the result of the cast is nullable.
2 changes: 1 addition & 1 deletion docs/topics/whatsnew14.md
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ For more information about default methods in the Java interop, see the [interop

Starting from Kotlin 1.4.0, all runtime null checks will throw a `java.lang.NullPointerException` instead of `KotlinNullPointerException`,
`IllegalStateException`, `IllegalArgumentException`, and `TypeCastException`. This applies to: the `!!` operator, parameter
null checks in the method preamble, platform-typed expression null checks, and the `as` operator with a non-null type.
null checks in the method preamble, platform-typed expression null checks, and the `as` operator with a non-nullable type.
This doesn't apply to `lateinit` null checks and explicit library function calls like `checkNotNull` or `requireNotNull`.

This change increases the number of possible null check optimizations that can be performed either by the Kotlin compiler
Expand Down

0 comments on commit b3026ad

Please sign in to comment.