Skip to content

Instantly share code, notes, and snippets.

@cavega
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavega/e8f465abc251801bf86c to your computer and use it in GitHub Desktop.
Save cavega/e8f465abc251801bf86c to your computer and use it in GitHub Desktop.
Kotlin Object with inner trait: instancing anonymous trait inside activity
// ** Kotlin implementation **
// Singleton with inner trait
object LastFmManager {
public trait TopArtistsFetchEvent {
public fun topArtistsFetchSucceeded(artists: List<LastFmArtist>)
public fun topArtistsFetchFailed(throwable: Throwable)
}
// Other logic here
}
// Android Activity
public class MainActivity : ActionBarActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
LastFmManager.fetchTopArtists(object : LastFmManager.TopArtistsFetchEvent(){ // Error in TopArtistFetchEvent's parenthesis: "This class does not have a constructor"
override fun topArtistsFetchSucceeded(artists: List<LastFmArtist>) {
throw UnsupportedOperationException()
}
override fun topArtistsFetchFailed(throwable: Throwable) {
throw UnsupportedOperationException()
}
})
}
}
// ** Java implementation
public class LastFmManager {
private static LastFmManager mInstance;
public interface TopArtistsFetchEvent {
public topArtistsFetchSucceeded(List<LastFmArtist> artists)
public topArtistsFetchFailed(Throwable throwable)
}
public static LastFmManager getInstance(){
if (mInstance == null) {
mInstance = new LastFmManager();
}
return mInstance;
}
private LastFmManager(){
}
}
public class MainActivity extends ActionBarActivity {
@Override
public void onCreate( Bundle savedInstanceState) {
LastFmManager.fetchTopArtists(new LastFmManager.TopArtistsFetchEvent(){
@Override
public void topArtistsFetchSucceeded(artists: List<LastFmArtist>) {
// Do something here
}
@Override
public void topArtistsFetchFailed(throwable: Throwable) {
// Report error
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment