What you have is lambda. It's a shortened form of writing some pieces of code. Of course, not everything has lambda, but this does. In your case, you create an anonymous class matching Dispatcher
.
With Java 8 language features (or Java 8 itself if you're not on Android) enables interfaces with one method, optionally annotated @FunctionalInterface, to be declared with lambda. I.e. this:
Runnable x = new Runnable() {
@Override public void run(){
// Foo bar
}
};
Is the same as:
Runnable x = () -> {
// Foo bar
};
This applies to all one-method interfaces. They can be annotated @FunctionalInterface, but it's not required.
Dispatcher is one, from the code you posted. The syntax is pretty basic:
() -> {
// () means 0 args. It can contain arguments if necessary
return "return value if applicable";
}
With arguments:
oneArg -> {
//Method body
}
(arg1, arg2) -> {
// MethodBody
}
Methods with return types can be simplified to one-liners if you feel like it:
() -> "some string return type"
And the same pattern with arguments; I'm not going to add examples for that again. The same as above still applies.
I've used varying parenthesis in this answer. There is actually some "rules" around the use of them. The compiler will complain if the syntax is wrong, but generally:
- One argument doesn't need () around it. It's optional here.
- Zero or two and up arguments require them.
It doesn't need explicit type declaration in Kotlin or Java; it's handled automatically. As for Java, it doesn't need i.e. int x
if the interface declares a function with an int argument.
There are some exceptions in Kotlin (I've encountered the compiler complaining it failed to infer types, just manually setting the type made it compile again), but there's not many.
Anyways, action
here is the single argument defined in the method. You're basically doing lambda-based inheritance, so you're required to have it in the method, but you don't have to use it (depending on your implementation).
In Kotlin, lambda for interfaces is slightly different. Interfaces declared in Java can be used in Kotlin lambda:
override fun create(store: Store<AppState>, nextDispatcher: Dispatcher) /*: Dispatcher*/
= Dispatcher { x -> //Arguments declared here
// add your actions here
}
However, this bug prevents Kotlin-declared interfaces from being declared this way. You'd need to use object : WhateverInterface
and add the body. (Encountered that in 1.2.70 too, so it's not fixed yet).