简介
Kotlin 是一个基于 JVM 的新的编程语言,由 JetBrains 开发。JetBrains,作为目前广受欢迎的 Java IDE IntelliJ 的提供商,在 Apache 许可下已经开源其Kotlin 编程语言。
特性- 轻量级: 这一点对于 Android 来说非常重要。项目所需要的库应该尽可能的小。Android 对于方法数量有严格的限制,Kotlin 只额外增加了大约 6000 个方法。
- 互操作: Kotlin 可与 Java 语言无缝通信。这意味着我们可以在 Kotlin 代码中使用任何已有的 Java 库;因此,即便这门语言还很年轻,但却已经可以使用成百上千的库了。除此之外,Kotlin 代码还可以为 Java 代码所用,这意味着我们可以使用这两种语言来构建软件。你可以使用 Kotlin 开发新特性,同时使用 Java 实现代码基的其他部分。
- 强类型: 我们很少需要在代码中指定类型,因为编译器可以在绝大多数情况下推断出变量或是函数返回值的类型。这样就能获得两个好处:简洁与安全。
- Null安全: Java 最大的一个问题就是 null。如果没有对变量或是参数进行null判断,那么程序当中就有可能抛出大量的 NullPointerException,然而在编码时这些又是难以检测到的。Kotlin 使用了显式的 null,这会强制我们在必要时进行 null 检查。
1、安装插件 选择这里的 Kotlin 相关的插件安装,安装完之后会要求你重新打开 Android Studio
2、重启完后在任意一个包下右键 New , 会发现多了一个 “Kotlin File/Class” 和 “Kotlin Activity”
- 根目录下的 build.gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
- app 目录下的 build.gradle:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.hkt.firstapp"
minSdkVersion 21
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.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'com.github.bumptech.glide:glide:4.12.0'
}