Why convert java to kotlin not working?


#1

Java code:

Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
        .readData(readRequest)
        .addOnSuccessListener(new OnSuccessListener() {
            @Override
            public void onSuccess(DataReadResponse dataReadResponse) {
                Log.d(LOG_TAG, "onSuccess()");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(LOG_TAG, "onFailure()", e);
            }
        })
        .addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                Log.d(LOG_TAG, "onComplete()");
            }
        });

Android studio 3.0.1 convert to kotlin:

Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
                    .readData(readRequest)
                    .addOnSuccessListener(object : OnSuccessListener {
                        fun onSuccess(dataReadResponse: DataReadResponse) {
                            Log.d(LOG_TAG, "onSuccess()")
                        }
                    })
                    .addOnFailureListener { e -> Log.e(LOG_TAG, "onFailure()", e) }
                    .addOnCompleteListener(object : OnCompleteListener {
                        override fun onComplete(task: Task<*>) {
                            Log.d(LOG_TAG, "onComplete()")
                        }
                    })

But it show error type mismatch at 2 rows: object : OnCompleteListener vs object : OnSuccessListener
"onComplete" override nothing.

How fix this errors?


#2

Hello @daitranthanhhoa he errors that come out of the code are due to the fact that you need the word “override” before the method “onSuccess” the code would look like this:

  Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this))
            .readData(readRequest)
            .addOnSuccessListener(object : OnSuccessListener {
                override fun onSuccess(dataReadResponse: DataReadResponse) {
                    Log.d(LOG_TAG, "onSuccess()")
                }
            })
            .addOnFailureListener (object: OnFailureListener{
                override fun onFailure(ex: Exception) {
                    Log.e(LOG_TAG, "onFailure()", ex)
                }
            })
            .addOnCompleteListener(object: OnCompleteListener {
                override fun onComplete(task: Task<*>) {
                    Log.d(LOG_TAG, "onComplete()")
                }
            })