Reputation: 393
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 ?
Upvotes: 3
Views: 1015
Reputation: 368
This is the syntax for a SAM conversion. It can be done because the Observer java interface only declares one method.
You can do this for Kotlin interfaces with this syntax in Kotlin 1.4+
Upvotes: 3
Reputation: 4048
The snippet you posted is called a SAM conversion. You're creating an object of interface type Observer<String>
by specifying it as a lambda expression.
In your specific case newName
is the parameter that is passed to the onChanged method, and seeing as the code defines it as Observer<String>
, is of type String
.
Upvotes: 4