Skip to content

Instantly share code, notes, and snippets.

@dkandalov
Created May 22, 2021 10:30
Show Gist options
  • Save dkandalov/80e854dd9394c588146590a542b69254 to your computer and use it in GitHub Desktop.
Save dkandalov/80e854dd9394c588146590a542b69254 to your computer and use it in GitHub Desktop.
Kotlin fun interfaces and the type system
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