Search code examples
androidkotlinrx-javarx-android

Type inference failed Kotlin rxjava map use


Trying to add a compositeDisposable. using the code that follows:

 compositeDisposable.add(
        animalsObservable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter { s -> s.toLowerCase().startsWith("c") }
            .map(object : Function<String, String>()
            {
                @Throws(Exception::class)
                fun apply(s: String): String
                {
                    return s.toUpperCase()
                }
            })
            .subscribeWith(animalsObserverAllCaps)
    )
    }

However, I get the following error:

Type inference failed: fun map(p0: Function!): Observable! cannot be applied to ()
Type mismatch: inferred type is but Function! was expected
One type argument expected for interface Function


Solution

  • I would expect it to be as simple as:

    .map { it.toUpperCase() }
    

    Instead of

    .map(object : Function<String, String>()
    {
        @Throws(Exception::class)
        fun apply(s: String): String
        {
            return s.toUpperCase()
        }
    })
    

    But anyway you're probably not using io.reactivex.functions.Function, hence the error. If you really don't want to use a lambda then:

    .map(object : io.reactivex.functions.Function<String, String> {
        override fun apply(t: String): String {
            return t.toUpperCase()
        }
    })
    

    Or just import io.reactivex.functions.Function and then use Function.