HyeonSeok
HyeonSeok

Reputation: 599

What is the differences between Nothing or Any in Kotlin

I want to know the differences between Nothing and Any

I have sealed class

sealed class Result<out R>() {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val errorMsg: String) : Result<Nothing>()
}

And this is the usage of Result class

fun <T>test(data: T) : Result2<T> {
    return Result2.Error("error")
}

If I change this

data class Error(val errorMsg: String) : Result<Nothing>()

To this

data class Error(val errorMsg: String) : Result<Any>()

An error occurs in test function (error message below)

Type mismatch.
Required: Result<T>
Found: Result.Error

Can type Nothing replace generic T?

Upvotes: 1

Views: 476

Answers (1)

Sergey Ushakov
Sergey Ushakov

Reputation: 186

Nothing is a class, that have no instances. In kotlin type system Nothing is considered as a subclass of all other class. Any is completely opposite. Every other class considered as subclass of Any.

In you function test you declared T as lower bound. But Any can't match, because it is lower then any other T. Remember: Any is parent for any other class.

Also take a loot at great blog post about kotlin type system: https://blog.kotlin-academy.com/the-beauty-of-kotlin-typing-system-7a2804fe6cf0

Upvotes: 1

Related Questions