Created
May 22, 2021 10:30
-
-
Save dkandalov/80e854dd9394c588146590a542b69254 to your computer and use it in GitHub Desktop.
Kotlin fun interfaces and the type system
This file contains hidden or 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
fun interface Action { | |
fun run() | |
} | |
fun schedule(action: Action) = action.run() | |
fun scheduleFun(action: () -> Unit) = action.invoke() | |
fun f(): Unit = println("foo") | |
fun main() { | |
// assignment | |
val action: Action = Action { println("foo") } | |
val action2: Action = { println("foo") } // Type mismatch. Required: Action Found: () → Unit | |
val action3: Action = ::f // Type mismatch. Required: Action Found: KFunction0<Unit> | |
val foo: () -> Unit = Action { println("foo") } // Type mismatch. Required: () → Unit Found: Action | |
// passed as an argument | |
schedule(Action { println("foo") }) | |
schedule { println("foo") } | |
schedule(::f) | |
schedule(Runnable { println("foo") }) // Type mismatch. Required: Action Found: Runnable | |
scheduleFun(Action { println("foo") }) // Type mismatch. Required: () → Unit Found: Action | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment