Skip to main content

Grammatical Gender with MessageFormat API

Android has MessageFormat API that enables you to create internationalized messages by selecting phrases based on keywords. One use case of this API is to create gender based inflection.

Purpose​

MessageFormat API is meant for strings that doesn't address the user directly. For strings that address the user, consider using Grammatical Inflection API instead.

Basic Usage​

Let's say that we have a simple method that returns a string:

fun describePerson(name: String): String {
return "$name likes cooking. He cooks a lot of food everyday."
}

Notice that this method uses masculine pronoun "He" to address the person, even though the person could be female or neuter.

We can update the method by using MessageFormat like this:

import android.icu.text.MessageFormat

fun describePerson(name: String, gender: String): String {
val pattern =
"{0} likes cooking. {1, select, female {She} male {He} other {It}} cooks a lot of food everyday."
val messageFormat = MessageFormat(pattern)
return messageFormat.format(arrayOf(name, gender))
}

If we run the method, the result will look like this:

import android.util.Log

Log.i("TAG", describePerson("John", "male")) // "John likes cooking. He cooks a lot of food everyday."
Log.i("TAG", describePerson("Jane", "female")) // "Jane likes cooking. She cooks a lot of food everyday."
Log.i("TAG", describePerson("Dog", "neuter")) // "Dog likes cooking. It cooks a lot of food everyday."

Notice that now the subject pronoun changes based on the given gender parameter.

References​