Kotlin 重构 - F6 not working?

原始代码

class RefactorClass {
    val data: RefactorData = RefactorData("lambeta")
    fun refactorIt() {
        println("hello, ${data.name}")
    }

}
data class RefactorData(val name: String)

目标代码

class RefactorClass {
    val data: RefactorData = RefactorData("lambeta")
    fun refactorIt() {
        data.sayHello()
    }

}

private fun RefactorData.sayHello() {
    println("hello, $name")
}

data class RefactorData(val name: String)

重构步骤如下:

  1. Extract method
  2. Convert member to extension (to top-level)
  3. Introduce parameter
  4. Convert parameter to receiver
  5. Move member

1. Extract method

Extract method

2. Convert member to extension (to top-level)

Option + Enter, Convert member to extension

3. Introduce parameter

Cmd + Option + p, Introduce parameter

4. Convert parameter to receiver

Option + Enter, Convert parameter to receiver

5. Move member

F6, Move member

小结

Kotlin 是一门函数式编程语言,函数是一等公民。多态其实是函数的固有属性,所以 Convert parameter to receiver 这种手法比较有用。

问题

至于怎么把 extension function inline to class 中,暂时还没有很好的快捷键支持,但是我们的目的已经达到了——数据结构和函数在同一个模块里。

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=doij4dlxf4pu

推荐阅读更多精彩内容