在 Kotlin 中 Class 的默认修饰符是 final,是不可以被继承和重写的,如果需要进行重写,可以在类名前面加修饰符 open,像下面这样:
open class RunClass {}当我们只需要一个构造函数的时候,可以直接有下面这种方式进行声明:
class CustomView(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : View(context, attrs, defStyleAttr) { }有时候一个构造函数不够用的时候,可以使用 constructor 来声明:
constructor(context: Context) : super(context) { init(context) } constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) { init(context, attributeSet) } constructor(context: Context, attributeSet: AttributeSet?, defstyle: Int) : super(context, attributeSet, defstyle) { init(context, attributeSet, defstyle) }在 kotlin 中是不支持 static 关键字的,不过提供了另一种方案:companion object 关键字里面的内容都代表静态,可以是静态变量也可以是静态函数
companion object { fun main(context: Context) { val child = ChildImpl() val run = RunClass(child) run.show(context, "haha") } }一般匿名内部类里面只有一个方法的时候,Kotlin 会默认帮我们转成 Lambda 表达式,但是有多个方法的时候,就需要我们自己来实现了,可以采用下面这种方式:
viewpager.addOnPageChangeListener(object: ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { } })最常用的比如 startActivity,我们在 Java 文件中,该如何启动 kotlin 中的 activity:
startActivity(Intent(activity, UserActivity::class.java))这些是目前自己开发中遇到的一些问题,基本可以满足一般的kotlin开发了,其他问题可以再查看 Kotlin 官方文档。
Kotlin中文教程文档