Hey guys, I have a Kotlin class with some reified ...
# android
s
Hey guys, I have a Kotlin class with some reified and equivalent normal functions:
Copy code
// Java fun
fun <T:E> registerEvent(cls:Class<T>, consumer: Consumer<T>) : Disposable {
        return this.listen(cls)
            .subscribe(consumer)
    }

// Kotlin fun (calls the java one)
inline fun <reified T:E> registerEvent(consumer: Consumer<T>): Disposable {
        return registerEvent(T::class.java, consumer)
    }
In java I have no problem calling
registerEvernt(SomeClass.class, this::consumerMethod)
, but in Kotlin, when I try to do a method reference for the consumer, the compiler gives me an error and says it returns a
KFunction1<SomeClass, Unit>
and the required parameter is
Consumer<SomeClass>
. Is there any way I can make the functions behave the same, or is the
inline
or something else making it impossible?
s
It’s the SAM conversion problem. When you pass a function in Kotlin, it can’t be passed like that to Java, but it’s wrapped to
KFunction1<>
I think you could define your consumer like this and then pass it, but I’d have to look more into the problem to be sure:
Copy code
val consumer = Consumer { ... }
s
@skoric, yes that’s how I do it currently, but I wanted to make it so I don’t have to do that… I tried making the function accept a lambda
(Consumer) -> Unit
as a consumer, but the subscribe method doesn’t have an override that accepts that… Oh well I guess I’ll have to live with it…