Last active
November 23, 2022 18:38
-
-
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...
This file contains 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
// 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; | |
} | |
}); |
This file contains 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
// "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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looks better using Scala, but it can be even better when the API you use is designed for Scala and not Java