How to return withStyle function from another function

24 views Asked by At

how I can write a function that return withStyle built-in function which belong to AnnotatedString class

I tried to use withStyle as it is and it worked but I had to copy paste a lot of code then I tried to write a function that return the hole AnnotatedString builder but it didn't work

private val specialWords = listOf<String>()
private val forbiddenWords = listOf<String>()

private fun String.sentenceAnnotatedString(): AnnotatedString {
    return buildAnnotatedString {
        val sentence = this@sentenceAnnotatedString

        val words = sentence.split(" ")
        words.forEach { word ->
            when {
                // if this string is in specialWords list
                specialWords.contains(word) -> {
                    withStyle(
                        style = SpanStyle(
                            color = Orange
                        )
                    ) {
                        append(word)
                    }
                }
                // if this string is in forbiddenWords list
                forbiddenWords.contains(word) -> {
                    withStyle(
                        style = SpanStyle(
                            color = Color.Red
                        )
                    ) {
                        append(word)
                    }
                }

                else -> {
                    withStyle(
                        style = SpanStyle(
                            color = White
                        )
                    ) {
                        append(word)
                    }
                }
            }
        }
    }
}
0

There are 0 answers