https://kotlinlang.org logo
h

holgerbrandl

01/12/2021, 6:32 PM
Is there a refactoring to introduce a lambda method parameter from a code selection?
c

christophsturm

01/12/2021, 9:14 PM
yes. “introduce functional parameter”
h

holgerbrandl

01/12/2021, 9:45 PM
Is it possible that this does not work outside of a class body, that is for functions inside a kt file?
c

christophsturm

01/12/2021, 10:50 PM
if you post an example where it is not working for you i can try it out 🙂
h

holgerbrandl

01/12/2021, 11:18 PM
Sure, with pleasure: Try to use the refactoring for the implementation in
foo
. This fails for me, but it works for
other
Copy code
fun foo(){
    println("huhu")
    val a = 1
}

class IntroTest {
    fun other(){
        println("huhu")
        val a = 1
    }
}
image.png
c

christophsturm

01/13/2021, 11:39 AM
works for me
if i select the val a=1 too it does not work because it makes no sense to put that into a lambda
h

holgerbrandl

01/13/2021, 12:05 PM
It may not make sense, but it is not syntactically wrong, so it's a bug in the refactoring imho
c

christophsturm

01/13/2021, 12:41 PM
it makes no sense because there is no way that idea can do this refactoring, and still produce compilable code.
h

holgerbrandl

01/13/2021, 1:12 PM
Sure, it's possible:
`
Copy code
class Something
        
        fun foo(builder: () -> Unit){
            builder()
        }

        foo{
            println("huhu")
            val a = Something()
        }
And it is also useful because the instantation of
Something
may have a side effect