工具
对kotlin的代码不清楚本质时,可以通过转换成java代码进行查看,这样便于理解kotlin关键子和java的转换
步骤:
选择Tools -> Kotlin -> Show Kotlin bytecode 显示出当前文件/类的字节码在Kotlin Bytecode页面点击Decompile,把字节码转换成Java类,基本就可以看清Kotlin代码编程java代码的实际功能了
常用关键字
val 不可变长量类似finalvar 可变变量 fun 方法修饰词is 类型判断,类似java中的instanceofas 用于类型转换constructor 构造函数
扩展函数/属性
标准函数/作用域函数
标准函数有apply、also、let、run、with选择标准函数经典图
示例如下:
private lateinit var refreshLayout: SwipeRefreshLayout
//apply关键字设置相应的属性后,返回布局文件
refreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout).apply {
setOnRefreshListener(OnRefreshListener { presenter.fetchData() })
isRefreshing = true
}
//let进行了空类型检测,且内部使用了it,无返回值
lesson.state?.let {
setText(R.id.tv_state,it.stateName())
var colorRes = R.color.playback
colorRes = when (it) {
Lesson.State.PLAYBACK -> R.color.playback
Lesson.State.LIVE -> R.color.live
Lesson.State.WAIT -> R.color.wait
}
//with内部使用了this,可忽略,且无返回值
with(findViewById<RecyclerView>(R.id.list)) {
layoutManager = LinearLayoutManager(this@LessonActivity)
adapter = lessonAdapter
addItemDecoration(DividerItemDecoration(this@LessonActivity,LinearLayout.VERTICAL))
}
静态函数
文件里的静态函数和文件里的
文件名:staticTest.kt
package com.xiaoma.hencoder.kotlin.samples
fun fileFunction(){
println("文件静态函数")
}
object FileClazz{
const val name="name"
fun testObject(){
println("文件里object 关键字方法")
}
}
fun main() {
fileFunction()
FileClazz.testObject()
println(FileClazz.name)
}
//执行结果如下
文件静态函数
文件里object 关键字方法
name
文件夹下的fileFuntion方法实际上是StaticTestKt类里的静态方法,对应的是public final class StaticTestKtobject关键字修改的FileClazz类,最终也是public final class FileClazz fileClazz下的方法和属性最终对应的都是静态的
conpanion object修饰为伴生对象,伴生对象在类中只能存在一个,类似于java中的静态方法,Java中使用类访问静态变量、静态方法
class TestCompanion {
val tag="TestCompanion"
fun getName():String{
function()
return tag
}
companion object {
const val NAME = "name"
fun function() {
println(NAME)
}
}
}
测试代码
fun main() {
TestCompanion.function()
println(TestCompanion.NAME)
}
测试结果如下:
name
name
companion object中的属性就是类中的静态属性companion object中的函数就是类中的静态函数
函数形参
fun say() {
println("Hello World")
}
fun say(name: String, pwd: String) {
println("Hello $name,Your pwd is $pwd")
}
fun say(name: String) {
println("Hello $name")
}
//无参函数调用
fun people(hello: () -> Unit) {
hello()
}
//两个参数函数调用
fun people(name: String, function: (msg: String) -> Unit) {
function(name)
// function(msg) //Unresolved reference: msg
}
//三个函数调用
fun people(name: String, pwd: String, function: (msg: String, pwd: String) -> Unit) {
function(name, pwd)
}
fun main() {
people { say() } //无参函数调用
people(::say) //无参函数调用
people("Java-head") { say("java") } //两个参数函数调用
people("Java-head") { say() } //两个参数函数调用
people("Android", "999", ::say) //三个参数函数调用
people { say("TCP/IP", "bcd") } //无参函数调用
}
总结:
::fun 代表把一个方法当作参数,传递到另外一个方法中使用,通俗说就是引用一个方法方法参数function:() ->Unit 表示无参方法传入,没有返回值;function:(msg:String) ->String 表示有一个参数,返回值是String方法参数function:(msg:String) -> Unit在方法体中msg不能调用含有方法参数时,如果方法体中调用方法参数时需要注意,定义的参数建议跟方法体的参数个数保持一致
参考:将函数作为参数传递 kotlin 双冒号::使用