Kotlin 快速回忆与实用对照(Java 转 Kotlin 完整版) 1. 基础语法与数据类型
功能
Java 写法
Kotlin 写法
说明
变量
String name = "Tom";
val name = "Tom"
(只读) / var name = "Tom"
(可变)
Kotlin 自动类型推断
可空类型
String s = null;
var s: String? = null
?
表示可为 null
常量
public static final int MAX = 10;
const val MAX = 10
编译期常量
延迟初始化
-
lateinit var name: String
只能用于非基本类型的 var
类型转换
(int) 3.14
3.14.toInt()
所有类型都是对象
类型检测
if (obj instanceof String)
if (obj is String)
结合智能类型转换
2. 控制结构 if / 三元运算 1 2 3 4 5 int max = a > b ? a : b;val max = if (a > b) a else b
when 替代 switch 1 2 3 4 5 6 7 8 when (x) { 0 -> println("Zero" ) 1 , 2 -> println("One or Two" ) in 3. .10 -> println("3~10" ) !in 0. .100 -> println("Out of range" ) is String -> println("String" ) else -> println("Other" ) }
3. 函数与参数 基本函数 1 2 3 4 5 fun sum (a: Int , b: Int ) : Int { return a + b } fun sum (a: Int , b: Int ) = a + b
默认参数 1 2 fun greet (name: String = "Guest" ) = println("Hello $name " )greet()
命名参数 1 2 fun draw (x: Int , y: Int , color: String ) { ... }draw(color = "red" , x = 10 , y = 20 )
可变参数 1 fun sum (vararg nums: Int ) = nums.sum()
4. 类与对象 类定义 1 2 3 4 5 6 open class Person (val name: String) { open fun speak () {} } class Student (name: String, val grade: Int ) : Person(name) { override fun speak () { println("I'm $name , grade $grade " ) } }
数据类(data class) 1 2 3 data class User (val name: String, val age: Int )val u = User("Tom" , 20 )println(u.copy(age = 21 ))
单例 1 2 3 object NetworkManager { fun connect () { ... } }
伴生对象(companion) 1 2 3 4 5 6 class Utils { companion object { fun staticMethod () { ... } } } Utils.staticMethod()
5. 接口与匿名类 1 2 3 4 5 6 interface Clickable { fun onClick () } val c = object : Clickable { override fun onClick () { println("Clicked" ) } }
6. 集合与函数式编程 1 2 3 4 5 6 7 8 9 val list = listOf(1 , 2 , 3 ) val mList = mutableListOf(1 , 2 ) list.filter { it % 2 == 0 } .map { it * it } .forEach { println(it) } val map = mapOf("a" to 1 , "b" to 2 )for ((k, v) in map) println("$k = $v " )
7. 空安全与 Elvis 运算符 1 2 3 val name: String? = "Tom" val length = name?.length ?: 0 println(name!!.length)
8. 扩展函数 1 2 fun String.lastChar () = this [length - 1 ]println("Hello" .lastChar())
9. 高阶函数与 Lambda 1 2 fun operate (x: Int , y: Int , op: (Int , Int ) -> Int ) = op(x, y)val sum = operate(2 , 3 ) { a, b -> a + b }
10. 作用域函数(let / run / apply / also / with)
函数
作用
返回
let
转换/链式处理
最后一行
run
执行代码块
最后一行
apply
初始化对象
对象本身
also
附加操作
对象本身
with
非扩展版本 run
最后一行
1 2 3 val str = "hello" str.let { println(it.uppercase()) } val p = Person("Tom" ).apply { speak() }
11. 协程基础(Java 无直接对应) 1 2 3 4 GlobalScope.launch { val data = withContext(Dispatchers.IO) { loadData() } println(data ) }
12. Android 常用 Kotlin 用法
ViewBinding 替代 findViewById
1 2 3 binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btn.setOnClickListener { ... }
1 class MyAdapter : ListAdapter <Item, VH >(DiffUtilCallback) { ... }
1 fun View.setOnDebouncedClickListener (delay: Long = 500 , action: (View ) -> Unit ) { ... }
1 val visibleItems = items.filter { it.isVisible }
好,那我帮你把刚才的 Java→Kotlin 对照速查再补齐到完整版本,把 Kotlin 比较“进阶”和“少见但强大”的特性也加上,包括委托、密封类、内联函数、泛型、操作符重载等,让你既能快速回忆,也能一步到位掌握新能力。
13. 密封类(sealed class)
1 2 3 4 5 6 7 8 9 10 sealed class Result data class Success (val data : String) : Result()data class Error (val e: Throwable) : Result()object Loading : Result()fun handle (r: Result ) = when (r) { is Success -> println("OK: ${r.data} " ) is Error -> println("Err: ${r.e} " ) Loading -> println("Loading..." ) }
对比 Java 的 enum
,密封类能携带不同数据类型,且可在 when
中强制穷尽所有分支。
14. 委托(by)
1 2 3 4 5 6 interface Logger { fun log (msg: String ) }class ConsoleLogger : Logger { override fun log (msg: String ) = println(msg) }class MyService (logger: Logger) : Logger by loggerval s = MyService(ConsoleLogger())s.log("Hello" )
1 2 3 4 val lazyValue: String by lazy { "computed" }var name: String by Delegates.observable("<no name>" ) { prop, old, new -> println("$old -> $new " ) }
15. 内联函数(inline)
消除高阶函数带来的对象创建与调用开销,常与 crossinline
、noinline
配合。
1 2 3 4 5 6 inline fun measureTime (block: () -> Unit ) { val start = System.nanoTime() block() println("Took ${System.nanoTime() - start} ns" ) } measureTime { println("Task" ) }
16. 泛型与 reified
reified
让泛型在运行时保留类型信息(仅限内联函数)。
1 2 3 4 inline fun <reified T> Gson.fromJson (json: String ) = this .fromJson(json, T::class .java) val user: User = gson.fromJson(jsonString)
17. 操作符重载
1 2 3 4 data class Point (val x: Int , val y: Int ) { operator fun plus (other: Point ) = Point(x + other.x, y + other.y) } val p = Point(1 , 2 ) + Point(3 , 4 )
18. 解构声明
类的 componentN()
方法支持直接拆解对象。
1 2 data class User (val name: String, val age: Int )val (n, a) = User("Tom" , 20 )
19. 匿名对象(object expression)与伴生对象 1 2 3 4 5 6 7 8 9 val listener = object : View.OnClickListener { override fun onClick (v: View ?) { println("Clicked" ) } } class Utils { companion object { fun staticMethod () = println("Static" ) } } Utils.staticMethod()
20. 类型别名
1 2 typealias ClickListener = (View) -> Unit fun setClick (listener: ClickListener ) { ... }
21. 中缀函数(infix)
1 2 infix fun Int .times (str: String ) = str.repeat(this )println(2 times "Bye" )
22. 内部函数(local function)
1 2 3 4 5 6 7 fun validate (user: User ) { fun check (value: String , name: String ) { if (value.isBlank()) throw IllegalArgumentException("$name empty" ) } check(user.name, "Name" ) check(user.email, "Email" ) }
23. 内部类与嵌套类
Kotlin 默认类是静态嵌套类,需要 inner
才能持有外部类引用。
1 2 3 4 class Outer { private val bar = 1 inner class Inner { fun foo () = bar } }
24. Android 场景下的 Kotlin 进阶用法 RecyclerView Adapter 极简 1 2 3 4 5 6 7 8 9 10 class UserAdapter : ListAdapter <User, UserAdapter.VH >(diffCallback) { class VH (val b: ItemUserBinding) : RecyclerView.ViewHolder(b.root) override fun onCreateViewHolder (p: ViewGroup , vt: Int ) = VH(ItemUserBinding.inflate(LayoutInflater.from(p.context), p, false )) override fun onBindViewHolder (h: VH , pos: Int ) = h.b.apply { val u = getItem(pos) name.text = u.name } }
View 点击去抖 1 2 3 4 5 6 7 8 9 10 fun View.onClickDebounce (delay: Long = 500 , block: (View ) -> Unit ) { var last = 0L setOnClickListener { val now = SystemClock.uptimeMillis() if (now - last >= delay) { last = now block(it) } } }
协程 + Retrofit 1 2 interface Api { @GET("users" ) suspend fun getUsers () : List<User> }val users = withContext(Dispatchers.IO) { api.getUsers() }
25. Java → Kotlin 迁移小技巧
保留 Java 逻辑结构 ,先让编译通过,再做语法优化。
优先替换 :
findViewById
→ ViewBinding
工具类静态方法 → 扩展函数
数据实体 → data class
集合遍历 → forEach
/ map
/ filter
空安全处理 :
逐步引入 协程,不要一次性重写所有异步逻辑。