What is "out" keyword in Kotlin?

Kotlin Mobile DevelopmentApps/Applications

"Out" keyword is extensively used in Kotlin generics. Its signature looks like this −

List<out T>

When a type parameter T of a class C is declared out, then C can safely be a super type of C<Derived>. That means, a Number type List can contain double, integer type list.

Example

The following example demonstrates how you can use the "out" keyword in Kotlin −

fun main(args: Array<String>) {
   var objet1 = genericsExample<Int>(10)
   var objet2 = genericsExample<Double>(10.0)
}

// As generic type is declared as "out",
// we can pass Int and Double also.

class genericsExample<out T>(input:Any?) {
   init {
      println("I am getting called with the value "+input)
   }
}

Output

It will produce the following output

I am getting called with the value 10
I am getting called with the value 10.0
raja
Updated on 23-Nov-2021 07:23:31

Advertisements