Friday 16 February 2018

Kotlin: complementary variance annotation: in

It is continuation to my previous post, I recommend you to go through my previous post before reading this.

When a type parameter T of a class C is declared ‘in’, C<Derived> can safely be a supertype of C<Base>. What it means is, for a reference of type T, we can able to assign the reference to the subtype of T.

var demoObjNumber: DemoObj<Number> = DemoObjImpl()

/* We can assing demoObjNumber to DemoObj<Double> reference */
var demoObjDouble: DemoObj<Double> = demoObjNumber

/* We can assing demoObjNumber to DemoObj<Int> reference */        
var demoObjInt: DemoObj<Int> = demoObjNumber

Find the below working application.

Test.kt
public interface DemoObj<in T> {
 fun toString(value: T): String
}

public class DemoObjImpl<in T> : DemoObj<T> {

 override fun toString(value: T): String {
  return value.toString()
 }

}

fun main(args: Array<String>) {
 var demoObjNumber: DemoObj<Number> = DemoObjImpl()
 var result = demoObjNumber.toString(10)
 println("result : $result")

 var demoObjDouble: DemoObj<Double> = demoObjNumber
 result = demoObjDouble.toString(10.01)
 println("result : $result")
 
 var demoObjInt: DemoObj<Int> = demoObjNumber
 result = demoObjInt.toString(10)
 println("result : $result")
}

Output
result : 10
result : 10.01
result : 10



Previous                                                 Next                                                 Home

No comments:

Post a Comment