"Extract property" in Kotlin don't work as expected


#1

I often use “Extract Field” (https://www.jetbrains.com/help/idea/extract-field.html) to declare member variable in Java, but this is not work in Kotlin as expected:

Before:

class Class {
  fun method() {
    val a = 1
    val b = 2
    var c = a + b
  }
}

When I select “c” and “Extract Field”, IDEA prompts “cannot introduce property for this expression”. I assumed it should goes:

class Class {
  var c1: String? = null
  lateinit var c2: String
  var c3 by Delegates.notNull<String>()

  fun method() {
    val a = "a"
    val b = "b"
    c1 = "$a $b"
    c2 = "$a $b"
    c3 = "$a $b"
 }
}

Is there any way to introduce an expression to a member variable using a built-in refactor function provided by IDEA when using Kotlin as language?

I asked questions at IDEA Forum(https://intellij-support.jetbrains.com/hc/en-us/community/posts/360001708260--Extract-Field-in-Kotlin-don-t-work-as-expected) before.They say the mentioned feature in IDEA editor is a Kotlin-specific and is provided by the Kotlin plugin.So I want to know whether this is an unfinished task or a feature?


#2

This is interesting. When I do the normal Ctrl+Alt+F thing it does what you describe. When I remove var, and Alt+Enter on c then I get the option to create the property, and it works.


#3

If I select the expression and try “Extract Property” it creates a local value/variable. Perhaps this should go on YouTrack?


#4

This is a known issue, please vote for https://youtrack.jetbrains.com/issue/KT-11672