问题
I'm just learning Java, and I've developed apps in Objective-C before. I like the concept of "blocks", because they allow code to be ran after something happens.
For example, to execute a block after a certain amount of time in a SpriteKit app that calls a method helloWorld
from scene myScene
:
[myScene runAction:[SKAction sequence:@[[SKAction waitForDuration:5], [SKAction runBlock:^{
[myScene helloWorld];
}]]]];
Is there anything like a block in Java? If so, how would I use it? What's the syntax to...
- use it as a function parameter?
- call said block in the function?
- assign a value to the block?
I've heard a little bit about "closures," but I'm not so sure what they are or how to use them.
回答1:
In Java, the way to do this is to use an interface. The most basic interface for this is Runnable
which has a method run
.
What's the syntax to...
use it as a function parameter?
void foo(Runnable r)
call said block in the function?
r.run();
assign a value to the block?
Before Java 8 you had to do something like this:
Runnable r = new Runnable() {
@Override
public void run() {
// do something
}
}
Now you can just do:
Runnable r = () -> { // do something }
An expression involving ->
is called a lambda. The brakets ()
are where you would write any parameters, but the method run
of Runnable
doesn't have any parameters. You can also pass a Runnable
to a method without mentioning Runnable
:
foo(() -> { // do something });
Java 8 introduced many, many new interfaces where the method can return a value or accept parameters.
来源:https://stackoverflow.com/questions/32997887/is-there-anything-like-an-objective-c-block-in-java