考虑我用 Kotlin 编写的一个简单测试:
class LocaleTest {
@Test fun english() {
val locale = Locale("en")
assertEquals("English", locale.displayLanguage)
assertEquals("en", locale.language)
}
@Test fun indonesia() {
val locale = Locale("id")
assertEquals("Indonesian", locale.displayLanguage)
assertEquals("id", locale.language)
}
}
第二个测试失败,因为它应该是 id
但实际上是 in
。这怎么可能? Locale
是用语言 id
构建的,假设它将返回相同的语言不是很安全吗?
最佳答案
来自Javadoc :
Note: ISO 639 is not a stable standard— some languages' codes have changed. Locale's constructor recognizes both the new and the old codes for the languages whose codes have changed, but this function always returns the old code.
如果您想检查其代码已更改的特定语言,请不要这样做
if (locale.getLanguage().equals("he")) // BAD!
相反,做
if (locale.getLanguage().equals(new Locale("he").getLanguage()))
关于java.util.Locale 返回它构建时使用的不同语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50371786/