为什么Kotlin的mutableListOf()返回空值
我正在通过 Google 的 Android 开发人员代码实验室为 unscramble 应用程序工作。我正在尝试将我的变量初始化wordsList为一个空的可变字符串列表:
private var wordsList: MutableList<String> = mutableListOf()
但是,在调试过程中,我看到wordsListis的值null而不是像[]. 我在 kotlin playground 中测试了代码,它应该是[]. 我附上了一张 android studio 向我展示的截图。我做错了什么,为什么我没有看到预期的行为?
这是我的项目的 gradle 文件:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.21"
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
以及我的应用程序的 gradle 文件
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.android.unscramble"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding = true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
// LiveData
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.fragment:fragment-ktx:1.2.5'
}
回答
参考Kotlin 文档:
在实例初始化期间,初始化块按照它们在类体中出现的顺序执行,与属性初始化器交错
因此,您的断点可能init { }在wordsList尚未初始化时从上块命中。您可以选择在调用之前初始化您的变量,getNextWord()或者只是将这个init { }块向下移动,以便在您的所有属性都已经初始化时执行它。