如何在Kotlin中创建2D Int数组?我正在try 将此代码转换为Kotlin:

int[][] states = new int[][] {
      new int[]{-android.R.attr.state_pressed}, // not pressed
      new int[] { android.R.attr.state_pressed}  // pressed
};
int[] colors = new int[] {
      foregroundColor,
      accentColor,
      accentColor
};
ColorStateList myList = new ColorStateList(states, colors);

Here is one attempt I tried, where the first 2D array didn't work, but I got the 1D array to work:

//This doesn't work:
var states: IntArray = intArrayOf(
    intArrayOf(-android.R.attr.state_pressed), // not pressed
    intArrayOf(android.R.attr.state_pressed)  // pressed
);
//This array works:
var colors: IntArray = intArrayOf(
    foregroundColor,
    accentColor,
    accentColor
);
val myList: ColorStateList = ColorStateList(states, colors);

推荐答案

You are trying to put your IntArrays inside another array to make it 2-dimensional. The type of that array cannot be intArray, which is why this fails. Wrap your initial arrays with arrayOf instead of intArrayOf.

val even: IntArray = intArrayOf(2, 4, 6)
val odd: IntArray = intArrayOf(1, 3, 5)

val lala: Array<IntArray> = arrayOf(even, odd)

Kotlin相关问答推荐

判断字符串是否除了.&" ",","@""""

Spring Boot Bean验证器未触发

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

合并状态流

Kotlin 基于参数类型的返回类型推断

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

在 Compose 中使用 Text() 时如何获取文本的大小?

从 Kotlin 调用 Java 时可以为空的规则是什么

Kotlin:不允许在辅助构造函数参数上使用val

在协程中等待侦听器内的数据

如何退出 Kotlinc 命令行编译器

Kotlin 具体化的泛型不会按计划保持类型

Kotlin的web-framework框架

main函数和常规函数有什么区别?

使用Dagger 2提供函数依赖性

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

uses-sdk:minSdkVersion 16 不能小于库中声明的版本 23

旋转 kotlin 数组

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

如何在 spring-boot Web 客户端中发送请求正文?