简体   繁体   中英

How do I create a list of objects in Kotlin?

I started Kotlin after Java.

I want to write a function to return Single<List<LocationData>>

override fun getDestinations(): Single<List<LocationData>> {
  //return ???
}

My LocationData class:

@Parcelize
data class LocationData(val latitude: Double, val longitude: Double) : Parcelable

How can I create a List of static LocationData objects in Kotlin?

In Java I would do this like this:

public ArrayList<LocationData> getDestinations(){
  ArrayList<LocationData> data = new ArrayList<>();
  LocationData location1 = new LocationData( 43.21123, 32.67643 );
  LocationData location2 = new LocationData( 32.67643, 43.21123 );
  data.add( location1 );
  data.add( location2 );
  return data;
}

最基本的方法是使用listOf函数(或mutableListOf ,如果您以后需要修改列表):

fun getDestinations() = listOf( LocationData( 43.21123, 32.67643 ), LocationData( 32.67643, 43.21123 ))

In Kotlin it will look like that:

fun getDestinations(): List<LocationData> {
    return listOf(
            LocationData(43.21123, 32.67643),
            LocationData(43.21123, 32.67643)
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM