Android 为什么Kotlin的mutableListOf()返回空值
我正在通过谷歌的Android开发者codelab开发解读应用程序。我正在尝试将变量wordsList初始化为空的可变字符串列表,其中包含: 私有变量wordsList:MutableList=mutableListOf 但是,在调试过程中,我看到wordsList的值为null,而不是像[]这样的空列表。我在kotlin游乐场测试了代码,应该是[]。我附上了android studio向我展示的屏幕截图。我做错了什么,为什么我没有看到预期的行为? 以下是我的项目的gradle文件:Android 为什么Kotlin的mutableListOf()返回空值,android,kotlin,Android,Kotlin,我正在通过谷歌的Android开发者codelab开发解读应用程序。我正在尝试将变量wordsList初始化为空的可变字符串列表,其中包含: 私有变量wordsList:MutableList=mutableListOf 但是,在调试过程中,我看到wordsList的值为null,而不是像[]这样的空列表。我在kotlin游乐场测试了代码,应该是[]。我附上了android studio向我展示的屏幕截图。我做错了什么,为什么我没有看到预期的行为? 以下是我的项目的gradle文件: // T
// 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'
}
指:
在实例初始化期间,将执行初始化程序块
与它们在类主体中出现的顺序相同,与
属性初始值设定项
因此,当wordsList尚未初始化时,可能会从上面的init{}块命中断点。您可以选择在调用getNextWord之前初始化变量,或者只是将此init{}块向下移动,以便在所有属性都已初始化时执行它。何时设置断点?您可能在初始化断点之前就设置了它。@marstran我已经更新了屏幕截图。断点位于应初始化的变量之后。哦,我的上帝。我想我看到了这个问题。@marstran所以我想这就引出了我的下一个问题:这些变量应该在init块中定义吗?