Skip to content

Instantly share code, notes, and snippets.

@bjornharrtell
Last active November 23, 2022 18:38
Show Gist options
  • Save bjornharrtell/5176872 to your computer and use it in GitHub Desktop.
Save bjornharrtell/5176872 to your computer and use it in GitHub Desktop.
Java vs. Scala example of callback implementation to animate on touch then do something when animation is finished (AndEngine SDK). I suggest that Java callback API and usage is boring because it requires a design pattern (Observer) and interfaces to define the API and classes to implement at all times...
// bad/lazy Java, too nested... should implement callback classes separately, but that also feels like overkill and leads to macaroni code
// other crap parts is that all interface methods needs implementation and ugly override annotations.
scene.setOnAreaTouchListener(new IOnAreaTouchListener() {
@Override
public boolean onAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea, float pTouchAreaLocalX, float pTouchAreaLocalY) {
if (pSceneTouchEvent.isActionDown()) {
scene.registerEntityModifier(new DelayModifier(1.0f, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
...
}
}));
}
return false;
}
});
// "equivalent" Scala, but is ok code (IMO) because functions are first class
def onAreaTouch(pSceneTouchEvent: TouchEvent, pTouchArea: ITouchArea, pTouchAreaLocalX: Float, pTouchAreaLocalY: Float) {
if (pSceneTouchEvent.isActionDown) {
def onFinished(pModifier: IModifier[IEntity], pItem: IEntity) {
...
}
val modifier = new DelayModifier(duration = 1.0f, onFinished = onFinished)
scene.registerEntityModifier(modifier)
}
}
scene.onAreaTouch(onAreaTouch)
@johansjoberg
Copy link

Looks better using Scala, but it can be even better when the API you use is designed for Scala and not Java

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment