54 lines
1.4 KiB
Plaintext
54 lines
1.4 KiB
Plaintext
![]() |
== Why is this an issue?
|
||
|
|
||
|
Kotlin uses the data type `Unit` to represent the absence of a value in a function or an expression.
|
||
|
It corresponds to the type `void` in Java or `unknown` in JavaScript.
|
||
|
While `Void` is available in Kotlin, it is a Java platform type and not equivalent to Java `void` but `java.lang.Void`.
|
||
|
|
||
|
Use `Unit` instead of `Void` because it represents the absence of a value in Kotlin.
|
||
|
|
||
|
=== What is the potential impact?
|
||
|
|
||
|
==== Wrong logic
|
||
|
|
||
|
`Void` is not equivalent to Java `void` but `java.lang.Void`.
|
||
|
|
||
|
==== Unnecessary platform dependency
|
||
|
|
||
|
`Void` is a platform type available only in the Java Runtime Environment.
|
||
|
|
||
|
== How to fix it
|
||
|
|
||
|
Replace `Void` with `Unit`.
|
||
|
|
||
|
=== Code examples
|
||
|
|
||
|
==== Noncompliant code example
|
||
|
|
||
|
[source,kotlin,diff-id=1,diff-type=noncompliant]
|
||
|
----
|
||
|
typealias NoValueFunction = () -> Void // Noncompliant, `Void` used
|
||
|
|
||
|
interface NoValueFunctions {
|
||
|
fun voidFunction1(): Void // Noncompliant, `Void` used
|
||
|
fun voidFunction2(): Void // Noncompliant, `Void` used
|
||
|
}
|
||
|
----
|
||
|
|
||
|
==== Compliant solution
|
||
|
|
||
|
[source,kotlin,diff-id=1,diff-type=compliant]
|
||
|
----
|
||
|
typealias NoValueFunction = () -> Unit // Compliant, `Unit` used
|
||
|
|
||
|
interface NoValueFunctions {
|
||
|
fun unitFunction1(): Unit // Compliant, `Unit` used
|
||
|
fun unitFunction2() // Compliant, `Unit` used implicitly
|
||
|
}
|
||
|
----
|
||
|
|
||
|
== Resources
|
||
|
|
||
|
=== Documentation
|
||
|
|
||
|
* https://kotlinlang.org/docs/functions.html#single-expression-functions[Kotlin Docs, Unit-returning functions]
|