【问题标题】:Change name from this@ on kotlin在 kotlin 上从 this@ 更改名称
【发布时间】:2018-07-18 18:18:43
【问题描述】:

我有以下情况,一个名为save的扩展函数来自Marker

1.代码

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)
    }
}

代码对我来说很好。

2。问题

要在save 方法中使用Marker 的实例,我需要使用this@save,但这个名称并不具有暗示性,乍一看,它不像Marker

3.问题

是否可以应用别名来代替this@save

非常感谢!

【问题讨论】:

    标签: android kotlin alias extension-function


    【解决方案1】:

    你可以只保存对一个命名良好的局部变量的引用:

    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。谢谢!
    • 再次感谢,但请参阅我自己的答案。很抱歉给我带来了任何问题!
    【解决方案2】:

    非常感谢@zsmb13 的支持,但我需要用我自己的答案来回答,因为我们所做的一切都是不必要的,只需使用属性本身,没有任何前缀,看这个:

    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)
        }
    }
    

    我为此感到尴尬,但我会继续提出问题以支持另一位开发人员。谢谢大家!

    【讨论】:

    • 确实,隐式使用外部this 也是一种选择。值得注意的是,当您嵌套多个范围很深并且您从外部抓取某些东西时,这可能会变得相当混乱。 (当然,它只有在没有内部作用域具有相同属性的情况下才有效。)
    【解决方案3】:

    .let 是一个选项:

    fun Marker.save() = this.let { marker ->
        ctx.database.use {
          insert("markers",
            "id" to marker.id,
            // etc
          )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2013-08-19
      • 2020-03-20
      相关资源
      最近更新 更多