Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anko: inner scope of apply, confusing property resolution

I'm writing an Android layout using Anko DSL. When defining a TextView, I wanted to make it center-aligned, so I wrote this:

verticalLayout {
    textView(R.string.txt_greeting).apply {
        gravity = Gravity.CENTER_HORIZONTAL // <- this should have changed the alignment
        textSize = 20.0f
    }
    //...
}

But the alignment didn't change. In debugger I saw that gravity is set for the LinearLayout which is the TextView's parent.

Changing the statement to either

textView(R.string.txt_greeting).let { it.gravity = Gravity.CENTER_HORIZONTAL }

and

textView(R.string.txt_greeting).apply { [email protected] = Gravity.CENTER_HORIZONTAL }

and even

textView(R.string.txt_greeting).apply { this.gravity = Gravity.CENTER_HORIZONTAL }

solves the problem, thus in the original code implicit this is definitely resolved to this@verticalLayout.

Why does this happen?

Do I misunderstand something in Kotlin lambdas or is it a bug in Kotlin or Anko?

like image 217
hotkey Avatar asked Nov 09 '22 00:11

hotkey


1 Answers

It was actually a bug in scoping.

The corresponding issue has been marked as fixed, so the fix is likely to appear in the next release.

like image 68
hotkey Avatar answered Nov 15 '22 06:11

hotkey