Configure → Plugins → Marketplace → 搜索 Kotlin → InstallCode → Convert Java File to Kotlin File (Ctrl+Alt+Shift+K)plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android' // Kotlin Android 插件
}
android {
// ...
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
// Kotlin Android Extensions (合成屬性) 已棄用,建議用 ViewBinding
}
content_main.xml<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
package com.steveyg.hellokotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.content_main.* // 合成屬性導入
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textview.text = "Hello Kotlin!" // 直接操作 ID,無需 findViewById
}
}
// Java 類
public class Demo {
public String getType() { return "Java"; }
public void setType(String t) {}
public void printInfo() {}
}
// Kotlin 使用
val demo = Demo()
demo.type = "Kotlin" // 自動識別 setter
val t = demo.type // 自動識別 getter
demo.printInfo() // 普通方法直呼
規則:getXxx/setXxx 自動映射為屬性 xxx,布爾型 isXxx 同理。
// Kotlin 類
class KotlinDemo {
fun getType(): String = "Kotlin"
@JvmStatic fun staticMethod() {} // 靜態方法需註解
@JvmField val CONST = "CONST" // 靜態常量
fun sayHello(@JvmName("greet") name: String) {} // 重命名避開關鍵字
}
// Java 使用
new KotlinDemo().getType();
KotlinDemo.staticMethod();
System.out.println(KotlinDemo.CONST);
| Java | Kotlin |
|---|---|
String s = "a"; | val s = "a" (不可變) / var s = "a" |
if (a == null) ... | a?.let { ... } / a ?: default |
for (int i=0; i<n; i++) | for (i in 0 until n) / repeat(n) { ... } |
new Thread(() -> {}).start() | thread { ... } |
list.stream().map().collect() | list.map { ... } |
var nonNull: String = "abc" // 編譯期保證非空
var nullable: String? = null // 可空類型
val len = nullable?.length ?: 0 // 安全調用 + Elvis 操作符
nullable!!.length // 強制非空 (拋 NPE 風險)
GitHub:helloKotlin | 本站下載:源碼包