I know how to do it by creating a loop but I wanted to know if there's an easier way?

for example, I want to create an array of Point and they will all have (0,0) or increment x,y by their index.

推荐答案

Array has a special constructor for such things:

/**
 * Creates a new array with the specified [size], where each element is calculated by calling the specified
 * [init] function. The [init] function returns an array element given its index.
 */
public inline constructor(size: Int, init: (Int) -> T)

It can be used for both of your use cases:

val points = Array(5) {
    Point(0, 0)
}
//[Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0), Point(x=0, y=0)]


val points2 = Array(5) { index->
    Point(index, index)
}
//[Point(x=0, y=0), Point(x=1, y=1), Point(x=2, y=2), Point(x=3, y=3), Point(x=4, y=4)]

Kotlin相关问答推荐

最好的方法来创建一个 map 在kotlin从两个列表

Kotlin接口方法默认值&;可传递依赖项

通过快捷键手动砍掉功能参数等

为何Kotlin标准库中的AND和OR函数不能像&&和||一样进行短路运算?

创建包含 3 个相同项目的列表/使用返回类型重复

如何在 Kotlin 中为类方法调用传递变量

kotlin 单例异常是好是坏?

是什么让 Kotlin 中的 String 类能够使用方括号?

多次运行espresso测试

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

未为任务启用 Gradle 构建缓存

Spring webflux bean验证不起作用

Kotlin 顶级函数与对象函数

如何设置两列recyclerview?

将 @Component.Builder 与构造函数参数一起使用

Kotlin内联扩展属性

如何在Kotlin中获得KType?

Android Kotlin 创建类实现 Parcelable 在 writeToParcel 方法的 override中给出错误

Kotlin中的Memoization功能

在 intelliJ 元素中集成 Kotlinx 协程