androidkotlinaliasextension-function

Change name from this@ on kotlin


I have the follow situation, an extension function named as save from Marker

1. The code

fun Marker.save(ctx: Context) {
    //database is an extension property from Context
    ctx.database.use {
        insert("markers",
                "id" to this@save.id,
                "latitude" to this@save.position.latitude,
                "longitude" to this@save.position.longitude,
                "name" to this@save.title)
    }
}

The code work fine to me.

2. The issue

To use the instance of Marker inside save method I need use this@save, but this name is not sugestive, in first view, it don't appear like Marker.

3. The question

Is possible apply an alias to use instead this@save?

Thanks a lot!


Solution

  • You could just save the reference to a well-named local variable:

    fun Marker.save(ctx: Context) {
        val marker = this
        //database is an extension property from Context
        ctx.database.use {
            insert("markers",
                    "id" to marker.id,
                    "latitude" to marker.position.latitude,
                    "longitude" to marker.position.longitude,
                    "name" to marker.title)
        }
    }