Pulkit Hans
Pulkit Hans

Reputation: 23

Function not reachable when called

val res = Response.Listener<String> {
    fun onResponse(s: String) {
        doOnSuccess(s)
    }
}

The function onResponse is never used (not reachable from inspection scope) in the program while toast is properly executable.

Upvotes: 1

Views: 129

Answers (3)

Alexey Romanov
Alexey Romanov

Reputation: 170713

It should be just

val res = Response.Listener<String> {
    doOnSuccess(it)
}

or alternatively

val res = object : Response.Listener<String> {
    override fun onResponse(s: String) {
        doOnSuccess(s)
    }
}

With your code, Kotlin sees it as the first form, except the body of the method just declares a function coincidentally called onResponse and does nothing else; it's the same as

Response.Listener<String> {}    

Upvotes: 1

Willi Mentzel
Willi Mentzel

Reputation: 29844

Problem

The problem is that you define an anonymous function onResponse in the lambda which is never invoked!

A solution:

val res = Response.Listener<String> {
    fun onResponse(s: String) {
        doOnSuccess(s)
    }
    onResponse(it) // invocation
}

The better solution:

Since your doOnSuccess seems to accept a String as single argument and it returns Unit, using a function reference is also possible.

val res = Response.Listener<String>(::doOnSuccess)

I did not test it, but in this case I think that you can even leave out the explicity type, because Kotlin can infer it from the function reference.

val res = Response.Listener(::doOnSuccess)

Upvotes: 0

Davide Cannizzo
Davide Cannizzo

Reputation: 3134

As @mTak stated, you missed the override modifier.

Here's the corrected code:

val res = Response.Listener<String> {
    override fun onResponse(s: String) {
      doOnSuccess(s)
    }
}

Upvotes: 2

Related Questions