Hi guys, I have `List` of `Pairs`. I am using this...
# compose
k
Hi guys, I have
List
of
Pairs
. I am using this list in
buildAnnotatedString
. Finding which one is just text and which one is link.
Copy code
val listOfPair = listOf(
    Pair("Text 1", "app"),
    Pair("Text 2", "link"),
    Pair("Text 3", "app"),
    Pair("Text 4", "link"),
    Pair("Text 5", "app"),
    ....//// more items in here
)
Copy code
val multipleString = buildAnnotatedString {
    listOfPair.forEachIndexed { _, item ->
        val (text, type) = item
        if (type == "app") {
            withStyle(style = SpanStyle(color = Color.DarkGray)) {
                append("$text\n")
            }
        } else if (type == "link") {
            withStyle(style = SpanStyle(color = Color.Blue)) {
                append("$text\n")
            }
        }
    }
}
Is there any better way to improve this?
e
I can't test it right now but you can use something like:
Copy code
val typeToColorMap = mapOf( 
    "app" to Color.DarkGray,
    "link" to Color.Blue
    )
val multipleString2 = buildAnnotatedString {
    listOfPair.forEach { item ->
        val (text, type) = item
        withStyle(style = SpanStyle(color = typeToColorMap[type])) {
            append("$text\n")
        }
    }
}
k
yeah looks nice. Thanks I got the idea..
r
As a side note, you can destructure the item right away:
Copy code
listOfPair.forEach { (text, type) ->
    withStyle(style = SpanStyle(color = typeToColorMap[type])) {
        append("$text\n")
    }
}
k
Nicce thanks
e
And if you want to avoid using strings as keys (error-prone) you can use enums:
Copy code
enum class TypeToColorMap( val color: Color) {
    app( Color.DarkGray),
    link (Color.Blue)
}

val listOfPair = listOf(
    Pair("Text 1", <http://TypeToColorMap.app|TypeToColorMap.app>),
    Pair("Text 2", TypeToColorMap.link),
    Pair("Text 3", <http://TypeToColorMap.app|TypeToColorMap.app>),
    //....more items in here
)
val multipleString = buildAnnotatedString {
    listOfPair.forEach { (text, type) ->
        withStyle(style = SpanStyle(color = type.color)) {
            AttributedStringBuilder.append("$text\n")
        }
    }
}
k
perfect. I'll try this one.. Thanks a million for guidance..