3

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!

Abner Escócio
  • 2,697
  • 2
  • 17
  • 36

3 Answers3

9

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)
    }
}
zsmb13
  • 85,752
  • 11
  • 221
  • 226
0

Thanks a lot @zsmb13 for support, but I need answer with my own answer because everythings that we doing are unecessary, just use the property itself, without any prefix, look this:

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

I fell embarrassed for this, but I go keep my question to support another developer. Thanks everybody!

Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
  • 2
    Indeed, using the outer `this` implicitly is also an option. Worth noting that this can get quite confusing when you are nested multiple scopes deep and you're grabbing something from an outer one. (And of course, it only works as long as no inner scopes have the same properties.) – zsmb13 Jul 19 '18 at 04:35
0

.let is an option:

fun Marker.save() = this.let { marker ->
    ctx.database.use {
      insert("markers",
        "id" to marker.id,
        // etc
      )
    }
}
Nino van Hooff
  • 3,677
  • 1
  • 36
  • 52