Last active
November 2, 2023 09:09
-
-
Save MaksimDmitriev/c72e5bebef89ca5f43f05a5459e71e4b to your computer and use it in GitHub Desktop.
Kotlin "in"
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
interface Consumer<in T> { | |
fun consume(param: T) | |
} | |
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
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) | |
} | |
} |
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
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