Created
April 30, 2020 16:46
-
-
Save Bloody-Badboy/74cbab49ec16ac15bbac7ce57387653c to your computer and use it in GitHub Desktop.
Kotlin IN OUT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.arpan.recycleview.drills.utils | |
/** | |
* **** OUT **** | |
* Let's say that we want to create a producer class that will be producing a result of some type T. | |
* Sometimes; we want to assign that produced value to a reference that is of a supertype of the type T. | |
* To achieve that using Kotlin, we need to use the out keyword on the generic type. It means that we | |
* can assign this reference to any of its supertypes. | |
* The out value can be only be produced by the given class but not consumed: | |
* | |
* | |
* **** IN **** | |
* Sometimes, we have an opposite situation meaning that we have a reference of type T and we want to | |
* be able to assign it to the subtype of T. We can use the in keyword on the generic type if we want | |
* to assign it to the reference of its subtype. The in keyword can be used only on the parameter | |
* type that is consumed, not produced: | |
* */ | |
open class Shape | |
open class Circle : Shape() | |
class SemiCircle : Circle() | |
fun main() { | |
val parameterizedProducer = ParameterizedProducer(Circle()) | |
val parameterizedProducer2 = ParameterizedProducer(SemiCircle()) | |
// Type mismatch: inferred type is ParameterizedProducer<Circle> but ParameterizedProducer<SemiCircle> was expected | |
// val producer: ParameterizedProducer<SemiCircle> = parameterizedProducer | |
val producer: ParameterizedProducer<Shape> = parameterizedProducer | |
val producer2: ParameterizedProducer<Shape> = parameterizedProducer2 | |
val parameterizedConsumer = ParameterizedConsumer<Shape>() | |
// Type mismatch: inferred type is ParameterizedConsumer<Circle> but ParameterizedConsumer<Shape> was expected | |
// val consumer: ParameterizedConsumer<Shape> = parameterizedConsumer | |
val consumer: ParameterizedConsumer<SemiCircle> = parameterizedConsumer | |
} | |
class ParameterizedProducer<out T>(private val value: T) { | |
/** | |
* We defined a ParameterizedProducer class that can produce a value of type T. | |
* */ | |
fun get(): T { | |
return value | |
} | |
} | |
class ParameterizedConsumer<in T> { | |
/** | |
* We declare that a toString() method will only be consuming a value of type T. | |
*/ | |
fun toString(value: T): String { | |
return value.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment