Android Kotlin string building question

snotnose

Ars Tribunus Militum
2,747
Subscriptor
Code:
fun main() {
    val count = beerLeft()
    val talk = getString(R.strings.beer_message)
    val msg = "$count $talk"
}

fun beerLeft(): Int {
    return 42
}

In strings.xml
       <string name="beer_message">bottles of beer</string>
My newbie question is, how do I make msg without using count and talk? That is, something like msg = "beerLeft() getString(R.strings.beer_message)".
 

Jonathon

Ars Legatus Legionis
16,541
Subscriptor
Put a placeholder (in this case, %d; i.e. %d bottles of beer) in your string in strings.xml, then pass count as the second argument to getString. So you end up with:

Java:
fun main() {
    val count = beerLeft()
    val talk = getString(R.strings.beer_message, count)
}

fun beerLeft(): Int {
    return 42
}

In strings.xml
       <string name="beer_message">%d bottles of beer</string>

If you want to get fancy, there's also a mechanism in Android to handle localized plurals; the docs there have a good example of how that works (with both the content in strings.xml and what you do in your code).

(More broadly, you have a handful of ways you can concatenate strings in Kotlin, including the one you've already discovered with string interpolation; this is the nominally "correct" way to do what you're trying to do, though, as it allows for localization where concatenating strings in code would not.)
 
Last edited: