I tried these in Kotlin REPL

var listA = listOf(null ,null)
var listB = [null, null]

The first line works fine as expected. On displaying listA I get:

[null, null]

第二行抛出以下错误:

error: cannot use 'Nothing?' as reified type parameter
var listB = [null,null]
            ^
error: unsupported [Collection literals outside of annotations]
var listB = [null,null]
            ^
error: unsupported [Array<Nothing> in return type is illegal]
var listB = [null,null]
            ^

当我try 使用非空类型时,

var listC = [1,2]

我得到这个错误:

error: unsupported [Collection literals outside of annotations]
var listC = [1,2]
            ^

我是Kotlin 的新手.有人能解释一下这是怎么回事吗?

推荐答案

From the Kotlin documentation on Collections:

Kotlin does not have dedicated syntax constructs for creating lists or sets. Use methods from the standard library, such as listOf(), mutableListOf(), setOf(), mutableSetOf().

There are no list literals currently for code outside of annotations.

Kotlin相关问答推荐

jOOQ Kotlin Coroutines - Select all and exists查询

如何定义一个函数来接受任何具有特定字段的数据类

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

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

循环中的每个元素都应填充行中可用的所有可用空间

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

正则表达式 FindAll 不打印结果 Kotlin

奇怪的 cotlin check Not Null 参数错误

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

Kotlin 方法重载

在粘贴时将 java 转换为 kotlin

如何退出 Kotlinc 命令行编译器

Foo::class.java 和 Foo::javaClass 有什么区别?

Dagger2 Qualifier 不适用于 Kotlin?

如何将命令行参数传递给Gradle Kotlin DSL

在调用Kotlin数据类中的超类构造函数之前访问函数

Kotlin-通过与属性列表进行比较来筛选对象列表

TornadoFX 中设置 PrimaryStage 或 Scene 属性的方法

Kotlin:测试中的 java.lang.NoSuchMethodError