Home > Software engineering >  In Kotlin get array member with their name like in JavaScripe
In Kotlin get array member with their name like in JavaScripe

Time:04-08

In Javascript an Array can contain an Object and we can call Object properties by their name. like

const person = {firstName:"John", lastName:"Doe", age:46};
let fN = person.firstName;

How can achieve this in Kotlin.

CodePudding user response:

You can either try using a mapOf or a custom Person object.

// mapOf
val person = mapOf("firstName" to "John", "lastName" to "Doe", "age" to 46)
val name = person.get("firstName")
print(name) // John

// Custom class
class Person(val firstname: String, val lastname: String, val age: Int)

val person2 = Person(firstname = "John", lastname = "Doe", age = 46)
print(person2.firstname) // John

CodePudding user response:

Thanks DarShan, mapOf seems good for my problem cos I have a Key String to call the properties. But why the below code is not working:

// mapOf
val methods = mapOf(
   "first" to mapOf("v1" to 15, "v2" to 15 ),
   "second" to mapOf("v1" to 18, "v2" to 17 )
)

print(methods.get("first").get("v1"))

CodePudding user response:

i think the best way is using data class


data class Person(val firstName:String ,val lastName:String, val age:Int)

val person1 = Person(firstName = "John", lastName = "Doe", age = 46)
val john = person1.firstName //print "John"

//you can use it in a list

val people = listOf(person1,person2,..)

  • Related