Tipo de Vazio em Kotlin
1. Introdução
Neste tutorial, aprenderemos sobre o tipoVoid no Kotlin e, essencialmente, outras maneiras de representar o vazio ou nada no Kotlin.
2. Void vsvoid - em Java
Para entender o uso deVoid em Kotlin, vamos primeiro revisar o que é um tipoVoid em Java ehow it is different from the Java primitive keyword void.
The Void class, as part of the java.lang package, acts as a reference to objects that wrap the Java primitive type void. Pode ser considerado análogo a outras classes de wrapper, comoInteger - o wrapper para o tipo primitivoint.
Agora,Void não está entre as outras classes de wrapper populares porque não há muitos casos de uso em que precisamos retorná-lo ao invés dovoid primitivo. Mas, em aplicações como genéricas, onde não podemos usar primitivas, usamos o sclassVoid .
3. Void em Kotlin
Kotlin is designed to be completely interoperable with Java and hence Java code can be used in Kotlin files.
Vamos tentar usar o tipoVoid do Java como um tipo de retorno em uma função Kotlin:
fun returnTypeAsVoidAttempt1() : Void {
println("Trying with Void return type")
}
Mas esta função não compila e resulta no erro abaixo:
Error: Kotlin: A 'return' expression required in a function with a block body ('{...}')
Esse erro faz sentido e uma função semelhante daria um erro semelhante em Java.
Para corrigir isso, vamos tentar adicionar uma declaração de retorno. Mas,since Void is a non-instantiable final class of Java, we can only return null from such functions:
fun returnTypeAsVoidAttempt2(): Void {
println("Trying with Void as return type")
return null
}
Esta solução também não funciona e falha com o seguinte erro:
Error: Kotlin: Null can not be a value of a non-null type Void
O motivo da mensagem acima é que, ao contrário do Java, não podemos retornarnull de tipos de retorno não nulos em Kotlin.
In Kotlin, we need to make the function return type nullable by using the ? operator:
fun returnTypeAsVoidSuccess(): Void? {
println("Function can have Void as return type")
return null
}
Finalmente temos uma solução que funciona, mas como veremos a seguir, existem maneiras melhores de alcançar o mesmo resultado.
4. Unit em Kotlin
Unit em Kotlin pode ser usado como o tipo de retorno de funções que não retornam nada significativo:
fun unitReturnTypeForNonMeaningfulReturns(): Unit {
println("No meaningful return")
}
Por padrão, Javavoid é mapeado para o tipoUnit em Kotlin. This means that any method that returns void in Java when called from Kotlin will return*Unit* — por exemplo a funçãoSystem.out.println() _._
@Test
fun givenJavaVoidFunction_thenMappedToKotlinUnit() {
assertTrue(System.out.println() is Unit)
}
Além disso,Unit is the default return type and declaring it is optional, portanto, a função abaixo também é válida:
fun unitReturnTypeIsImplicit() {
println("Unit Return type is implicit")
}
5. Nothing em Kotlin
Nothing é um tipo especial em Kotlin usado para representar um valor que nunca existe. If a function’s return type is Nothing then that function doesn’t return any value not even the default return type Unit.
Por exemplo, a função abaixo sempre gera uma exceção:
fun alwaysThrowException(): Nothing {
throw IllegalArgumentException()
}
As we can appreciate, the concept of the Nothing return type is quite different and there is no equivalent in Java. No último, uma função sempre terá como padrão o tipo de retornovoid, embora possa haver casos como o exemplo acima, quando essa função pode nunca retornar nada.
The Nothing return type in Kotlin saves us from potential bugs and unwarranted code. Quando qualquer função comNothing como o tipo de retorno é invocada, o compilador não será executado além desta chamada de função e nos dará o aviso apropriado:
fun invokeANothingOnlyFunction() {
alwaysThrowException() // Function that never returns
var name="Tom" // Compiler warns that this is unreachable code
}
6. Conclusão
Neste tutorial, aprendemos sobrevoid vsVoid em Java e como usá-los em Kotlin. Também aprendemos sobre os tiposUniteNothing e sua aplicabilidade como tipos de retorno para diferentes cenários.
Como sempre, todo o código usado neste tutorial está disponívelover on Github.