如何在 Kotlin 中创建对象列表?

Coo*_*ter -2 kotlin

我在 Java 之后开始使用 Kotlin。

我想写一个函数来返回 Single<List<LocationData>>

override fun getDestinations(): Single<List<LocationData>> {
  //return ???
}
Run Code Online (Sandbox Code Playgroud)

我的LocationData班级:

@Parcelize
data class LocationData(val latitude: Double, val longitude: Double) : Parcelable
Run Code Online (Sandbox Code Playgroud)

如何在 Kotlin 中创建List静态LocationData对象?

在 Java 中,我会这样做:

override fun getDestinations(): Single<List<LocationData>> {
  //return ???
}
Run Code Online (Sandbox Code Playgroud)

RoT*_*oRa 8

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

fun getDestinations() = listOf( LocationData( 43.21123, 32.67643 ), LocationData( 32.67643, 43.21123 ))
Run Code Online (Sandbox Code Playgroud)


Bra*_*bra 5

在 Kotlin 中它看起来像这样:

fun getDestinations(): List<LocationData> {
    return listOf(
            LocationData(43.21123, 32.67643),
            LocationData(43.21123, 32.67643)
    )
}
Run Code Online (Sandbox Code Playgroud)