Why can't Lambda Observers?

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 Likes

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

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

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

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.

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

1 Like

I’m running into same issue and unable to figure it out. I posted the same question on stackoverflow a few days before →