Home > Net >  Difference between 'Reified' and 'Any' types in Kotlin
Difference between 'Reified' and 'Any' types in Kotlin

Time:01-06

I have some confusion about the differences in between reified and any types in Kotlin.

I have some info about the meaning of the keyword but not sure at which cases we can choose the refined? and which case to use any?

Can any one help me to specific answer on that?

CodePudding user response:

Reified keyword in Kotlin

To access the information about the type of class, we use a keyword called reified in Kotlin. In order to use the reified type, we need to use the inline function .

If a function is marked as inline , then wherever the function is called, the compiler will paste the whole body of the function there.

Example

inline fun <reified T> genericsExample(value: T) {
    println(value)
    println("Type of T: ${T::class.java}")
}
fun main() {
    genericsExample<String>("Learning Generics!")
    genericsExample<Int>(100)
}

Any

Object is the root of the class hierarchy in Java, every class has Object as a superclass. In Kotlin theAny type represents the super type of all non-nullable types.

It differs to Java’s Object in 2 main things:

  • In Java, primitives types aren’t type of the hierarchy and you need to box them implicitly, while in Kotlin Any is a super type of all types.

  • Any can’t hold the null value, if you need null to be part of your variable you can use the type Any?

java.lang.Object methods toString, equals and hasCode are inherited fromAny while to usewait and notify you will need to cast your variable to Object to use them.

Example

public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
    if (this is Collection && isEmpty()) return false
    for (element in this) if (predicate(element)) return true
    return false
}

public inline fun <T> Sequence<T>.any(predicate: (T) -> Boolean): Boolean {
    for (element in this) if (predicate(element)) return true
    return false
}
  • Related