Why can't Lambda Observers?


#1

Hey guys. Yesterday I started to work with the new LiveData api from Google.
But I am having a small issue. Not an issue at all, pehaps it is just something I am missing and would like you guys help me to understand it.

Check this code:

myList.observe(this@MainActivity, Observer {
                mBind.textView.text = it?.joinToString(separator = "\n")
            })

The “Observer” objet is a SAM JAVA interface declared as below:

public interface Observer<T> {
    /**
     * Called when the data is changed.
     * @param t  The new data
     */
    void onChanged(@Nullable T t);
}

For some reason I can’t lambda it just like below:

myList.observe(this@MainActivity) {
                    mBind.textView.text = it?.joinToString(separator = "\n")
                }

Anytime I try to lambda it, the compiler gives error. What am I missing? SAM interfaces should be able to lambda right?
All my code is working fine, just this observer object is causing issues.

Can someone explain me why I can’t lambda it?


#2

There is a “)” in the last line, is that a typo just here or in the code as well?


#3

Eliote it is just a typo. I will edit it.


#4

Hi guys!

I still have the problem described by shinayser.
When I don’t specify Observer before the lambda Android Studio says:

Type mismatch.
Required: Observer<String!>
Found: (???) -> Unit


#5

I’m having the same issue, and honestly I have no clue why that happens. It’d be cool if someone from Kotlins core devs responded.


#6

From what I can see, this happens because of this issue: https://youtrack.jetbrains.com/issue/KT-14984