Kotlin object initialization?

I’m just learning Kotlin and while diving in the Android docs I bumped into a weird syntax. At first I thought is a SAM but it does not look like it. This is the object:

internal class MyLocationListener(
        private val context: Context,
        private val callback: (Location) -> Unit
) {
}

And this is how is instantiated in a method:

 class MyActivity : AppCompatActivity() {
    private lateinit var myLocationListener: MyLocationListener

    override fun onCreate(...) {
        myLocationListener = MyLocationListener(this) { location ->
            // update UI
        }
    }
}

I do not understand how MyLocationListener is instantiated here, it provides the first parameter Context in the object instantiation and the second parameter is provided in the object body. For example in Java we have both of the parameters provided in the object instantiation:

 public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, (location) -> {
            // update UI
        });
    }

Could you point me where I could find this syntax explained in the docs ? Thanks.

See here

Passing trailing lambdas

In Kotlin, there is a convention: if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:

val product = items.fold(1) { acc, e -> acc * e }

Such syntax is also known as trailing lambda .

If the lambda is the only argument to that call, the parentheses can be omitted entirely:

run { println("...") }
5 Likes