Hey guys! I am currently converting some java cod...
# android
f
Hey guys! I am currently converting some java code to kotlin for my app and i have a question regarding Callbacks vs Closures. My java code uses a callback: Ex:
Copy code
public interface Callback {
   void onSuccess(Class item);
   void onError(Error error);
}
I was thinking of replacing this callback with a closure instead and my question is if it is better to add two closure parameters or to just have one? Is there a best practice for this? Ex:
Copy code
onSuccess: (item: Class) -> Unit, onError: (error: Error) -> Unit
OR
callback: (item: Class, error: Error) -> Unit
/Thanks
o
I don’t think there is universal “better” answer. Sometimes you might want to use Java-like listeners and anonymous objects, sometimes two lambdas, may be
sealed
hierarchy and single lambda with a
Result
parameter, or even a DSL builder for complex cases. Mostly it depends on how often do you use this event source: if it’s only couple of places, choose whatever is simpler. If it’s public facing API and/or there are many places you subscribe to the event then you might want to invest a little into usability.
f
Ok, then i’ll play around with closures and see what better fits my purpose 🙂 Thanks