Last active
August 29, 2015 14:18
-
-
Save cavega/e8f465abc251801bf86c to your computer and use it in GitHub Desktop.
Kotlin Object with inner trait: instancing anonymous trait inside activity
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
// ** 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