Search code examples
kotlinkotlin-android-extensionskotlin-extension

Kotlin, set value to TextView use callback interface


Such mini example, in Java I have:

 public static void getPlaceName(GoogleApiClient mGoogleApiClient, String placeId, @NonNull PlaceNameCallback callback) {
        Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
                .setResultCallback(places -> {
                    if (places.getStatus().isSuccess() && places.getCount() > 0) {
                        Place myPlace = places.get(0);
                        callback.onPlaceDetected(String.valueOf(myPlace.getName())); // set place name
                    }
                    places.release();
                });
    }

    public interface PlaceNameCallback {
        void onPlaceDetected(String name);
    }

And then I can set place name to TextView:

    getPlaceName(mGoogleApiClient, arrivalId[0], name -> textArrival.setText(name));

Please tell me how to set place name like this on Kotlin?


Solution

  • This thing is called SAM(single abstract method) and it's all about Java world. In a current version of Kotlin you can't use SAM like that if your interface was declared in Kotlin. They're using a high order functions instead of interfaces for this purpose. But also, as I know, in 1.3 version of Kotlin we probably will get this possibility(this info was taken from an interview with one of Kotlin developer from JetBrains, if you're familiar with Russian language, you can see this post here: https://habrahabr.ru/company/redmadrobot/blog/351516/)

    Btw, you can use SAM in Kotin, but only if your interface was declared in Java. For your example it should look like this:

    getPlaceName(mGoogleApiClient, arrivalId[0], PlaceNameCallback { textArrival.setText(it)})