Last active
October 14, 2021 02:25
-
-
Save sssurvey/0de6a3c376b29020f94c09b74aeb7cf6 to your computer and use it in GitHub Desktop.
The role of "Nothing" when dealing with generics and its use
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 Base<out A> { | |
fun someMethod(operation: (A) -> String): String | |
} | |
class Impl1<A>(val a: A): Base<A> { // could be a none empty node in linked list | |
override fun someMethod(operation: (A) -> String): String { | |
return "impl1 hahaha ${operation.invoke(a)}" | |
} | |
} | |
class Impl2: Base<Nothing> { // could be an empty node in linked list | |
override fun someMethod(operation: (Nothing) -> String): String { | |
return "impl2 hahaha NOTHING" | |
} | |
} | |
/** | |
* Terminal output: | |
* $ impl1 hahaha 0 | |
* $ impl2 hahaha NOTHING | |
*/ | |
fun main() { | |
val interface1: Base<Int> = Impl1<Int>(0) //intentionally verbose | |
val interface2: Base<Int> = Impl2() | |
interface1.someMethod { it.toString() }.also { println(it) } | |
interface2.someMethod { it.toString() }.also { println(it) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment