noe256471
noe256471

Reputation: 75

Move some line of codes inside with() function in Kotlin

For simplify reason, could I move some line of codes inside with() function like below?

// from this
val params: RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
params.addRule(RelativeLayout.ALIGN_PARENT_TOP)
textView.layoutParams = params
// to this inside with()
textView.layoutParams = with() {
    ...
}

Upvotes: 0

Views: 66

Answers (1)

Y.Kakdas
Y.Kakdas

Reputation: 843

You can do.

with(RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)){
    addRule(RelativeLayout.ALIGN_PARENT_TOP)
    textView.layoutParams = this
}

or,

textView.layoutParams = with(RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)){
    addRule(RelativeLayout.ALIGN_PARENT_TOP)
    this
}

or,

RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
    addRule(RelativeLayout.ALIGN_PARENT_TOP)
    textView.layoutParams = this
}

or,

textView.layoutParams = RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply {
    addRule(RelativeLayout.ALIGN_PARENT_TOP)
}

Upvotes: 1

Related Questions