https://kotlinlang.org logo
Title
t

therealbluepandabear

10/29/2021, 11:41 AM
Because one could argue that using 'with' could cause some readability issues.
t

Tobias Suchalla

10/29/2021, 11:56 AM
I would say that 
with
 is idiomatically 'wrong', you would rather use 
apply
 here because you are directly editing the object:
binding.apply {
    mImageView.setImageBitmap(item.bitmap)
    mdate.text = item.dateCreated

    mtext.apply {
        if (data[position].title.length > 6) {
            ellipsize = TextUtils.TruncateAt.MARQUEE
            isSelected = true
            isSingleLine = true
            text = (item.title + " ".repeat(10)).repeat(200)
        } else {
            text = item.title
        }
    }
}
Other than that, 
apply
 is perfectly valid and idiomatic here. If you actually want the two levels of 
apply
 here is up to you.
with
, however, is rather for situations where you want to bring an object into scope for other calculations (i.e., more or less read only):
val myColor = with(MaterialTheme.colors) {
    if (myCondition) primary else secondary
}
1
t

therealbluepandabear

10/29/2021, 12:02 PM
Makes sense
j

Joffrey

11/19/2021, 12:42 PM
Sorry I'm late to the party but when the piece of code wrapped in
with
or
apply
is long and mixed in other business logic like this, I would actually really go for an extension function instead
:yes-black: 2
t

therealbluepandabear

02/05/2022, 12:28 AM
Thanks for the feedback 🙂