Kotlin如何创建动态对象 [英] Kotlin How to create dynamic Object
问题描述
在javascript中,我们可以做类似的事情
In javascript we can do something like this
function putritanjungsari(data){
console.log(data.name)
}
let data = {
name:"putri",
div:"m4th"
}
putritanjungsari(data)
在kotlin中,我正在创建一个接受对象作为参数的函数,然后稍后读取其属性,如何在kotlin中以JVM为目标呢?
In kotlin, i'am creating a function that accept an object as parameter then read it's properties later, how to do that in kotlin that targeting JVM?
推荐答案
如果我正确理解了您的问题,则您尝试使用一个变量,该变量将键与某个值相关联,或者如果找不到键,则该键为undefined(kt中为null).您正在搜索地图 如果您不知道想要什么类型,可以制作任何类型的地图?所以
If I understood your question correct, you are trying to have a variable that associates keys with some value or undefined(null in kt) if none are found. You are searching for a Map If you don't know what types you want, you can make a map of type Any? So
Map<String, Any?>
哪些也是可空的
Map<String, Any>
如果您不希望为空
例如,您的代码:
fun putritanjungsari(data: Map<String, Any?>){
print(data["name"])
}
val data: Map<String, Any?> =mapOf(
"name" to "putri",
"div" to "m4th"
)
putritanjungsari(data)
请注意,您不能在此处添加新键或编辑任何数据,默认映射是不可变的.有MutableMap(实现方式相同,只是它具有放置新数据的方法)
Note that you can't add new keys or edit any data here, the default map is immutable. There is MutableMap (which is implemented the same, only it has a method to put new data)
这篇关于Kotlin如何创建动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!