我开始使用 Kotlin 进行 Android 开发。我对某些概念有疑问。
我在条件语句中使用“->”,但我不知道在这个例子中这意味着什么:
XmlPullParser.START_TAG -> {...}
XmlPullParser.TEXT -> textValue = xpp.text
XmlPullParser.END_TAG -> {...}
全部代码为:
val factory = XmlPullParserFactory.newInstance()
factory.isNamespaceAware = true
val xpp = factory.newPullParser()
xpp.setInput(xmlData.reader())
var eventType = xpp.eventType
var currentRecord = FeedEntry()
while (eventType != XmlPullParser.END_DOCUMENT) {
val tagName = xpp.name.toLowerCase()
when (eventType) {
XmlPullParser.START_TAG -> {
Log.d(TAG, "parse: Starting tag for " + tagName)
if (tagName == "entry") {
inEntry = true
}
}
XmlPullParser.TEXT -> textValue = xpp.text
XmlPullParser.END_TAG -> {
Log.d(TAG, "parse: Ending tag for " + tagName)
if (inEntry) {
when (tagName) {
"entry" -> {
applications.add(currentRecord)
inEntry = false
currentRecord = FeedEntry()
}
"name" -> currentRecord.name = textValue
"artist" -> currentRecord.artist = textValue
"releasedate" -> currentRecord.releaseDate = textValue
"summary" -> currentRecord.summary = textValue
"image" -> currentRecord.imageURL = textValue
}
}
}
}
最佳答案
这只是 syntax对于 Kotlin when expression .
基本上,它会检查 when ()
中的条件,如果匹配则执行 ->
之后的 block 。
您可以“内联”必须执行的代码或将其包装在花括号中。
另见 this example (Kotlin Playground)并将 aString
更改为另一个值。
关于android - 箭头在 Kotlin 中的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568836/