Kotlin syntax meaning?

I’m right now learning Kotlin for Android development coming from .NET C#. I have an issue regarding the Kotlin syntax, for example this:

 val nameObserver = Observer<String> { newName ->

            nameTextView.text = newName

This code is taken from Android LiveData Documentation. I think Observer is a new object, without the new keyword, as it does not exists in Kotlin. My problem is the lambda part. Is this a property that is initialized in the object ? How do I know which property is initialized without naming them , are they taken in order ? What is supposed to be newName in this context, the nameObserver value or something else ?

Sorry if this sounds like a dumb question, I’m just learning Kotlin. I know the answer is hidden somewhere in the Kotlin documentation, I just did not figured it out by reading the docs. :pensive:

1 Like

That’s a SAM conversion. See:

You’re telling the compiler that your lambda is atually of type Observer<String> which has a single abstract method.


Thanks for the explication and doc reference. In the kotlin docs “object” is also used in the syntax: object : IntPredicate . In the Android example “object” is not used. So I guess there is no need for “object” notation ? Also, the lambda that I write basically overrides the abstract onChanged method ?

The docs make example of both. object is necessary when you have more than one method to override/implement. Otherwise you can choose.
From experience I haven’t used this syntax often, in these cases you can just inline nameObserver and the compile will figure out its type on its own.

And yes, you’re implementing onChanged

1 Like