Skip to content

Instantly share code, notes, and snippets.

@MaksimDmitriev
Last active November 2, 2023 09:09
Show Gist options
  • Save MaksimDmitriev/c72e5bebef89ca5f43f05a5459e71e4b to your computer and use it in GitHub Desktop.
Save MaksimDmitriev/c72e5bebef89ca5f43f05a5459e71e4b to your computer and use it in GitHub Desktop.
Kotlin "in"
interface Consumer<in T> {
fun consume(param: T)
}
class SampleTest {
@Test
fun foo() {
val numberConsumer = object : Consumer<Number> {
override fun consume(param: Number) {
println("number: $param")
}
}
val intConsumer = object : Consumer<Int> {
override fun consume(param: Int) {
println("Int: $param")
}
}
demo(numberConsumer) // not possible without "in" in Consumer
demo(intConsumer)
}
private fun demo(consumer: Consumer<Int>) {
consumer.consume(1)
}
}
class Baz<in T> {
private var otherData: T? = null
fun set2(data: T) {
otherData = data
}
}
// Usage
class SampleTest2 {
@Test
fun check() {
val baz = Baz<Int>()
val bazN = Baz<Number>()
handleBaz(baz, 1)
handleBaz(bazN, 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment