类
定义类
使用class
声明类
class Invoice { }
// 如果一个类没有类体,可以省略花括号。
class Empty
构造函数
在 Kotlin 中的一个类可以有一个主构造函数和一个或多个次构造函数。
主构造函数是类头的一部分:它跟在类名(和可选的类型参数)后。
直接调用构造函数来创建类的实例,Kotlin中没有new
关键字
// 主构造函数写在类名后
class Class1 constructor(firstName: String)
// 如果主构造函数没有任何注解或者可见性修饰符
// 可以省略这个 constructor 关键字。
class Class2(firstName: String)
// 主构造函数不能包含任何的代码
// 初始化的代码可以放到以 init 关键字作为前缀的初始化块中
class Person(name: String) {
var age = 20
init {
println("name = $name, age = $age")
}
fun hello() {
println("hello")
}
// 声明次构造函数 需要直接或通过其他次构造函数间接调用主构造函数
constructor(name: String, age: Int) : this(name) {
this.age = age
}
}
fun main(args: Array<String>) {
val p = Person("fff")
p.age = 21
p.hello() //hello
}
函数
fun 函数名(参数列表): 返回值类型 { 函数体 }
fun 函数名(参数列表): 返回值类型 = 返回值表达式
- 无返回值时,返回值类型可省略
- 使用返回值表达式作为函数体且返回类型可有编译器推断时,返回值类型可省略
- 使用函数名(参数)
或对象名.函数名(参数)
调用函数
- 参数可以有默认值
- 调用函数时,可以指定参数名
fun function(i: Int, a: Int = 1, b: Int = 10): Int{
return i + a + b
}
fun main(args: Array<String>) {
println(function(123)) // 134
println(function(123, b = 20)) // 144
}
中缀表示法调用函数
如果一个函数
- 是成员函数或扩展函数
- 只有一个参数
- 用infix
关键字标注
那么这个函数可以用对象A 函数名 对象B
的方式调用,等同于对象A.函数名(对象B)
infix fun Int.addToString(i: Int): String{
return this.toString() + i.toString()
}
fun main(args: Array<String>) {
println(123 addToString 456) // 123456
println(345.addToString(321)) // 345321
}
重载
Kotlin允许使用默认参数来减少重载数量
fun foo(i:Int, n = 123) {
}
fun foo(s:String) {
}
fun main(args: Array<String>) {
foo(123)
foo(123, 234)
foo("str")
}
面向对象编程
可见性修饰符
- private
仅自己可见
- protected
在子类中可见
- internal
在同一模块中可见
- public
随处可见
Kotlin的默认可见性是public
继承
Kotlin中所有类的共同超类是Any
允许继承的类和成员要声明为open
,未声明open
的类和成员默认是final
使用class 类名() : 要继承的父类()
继承
重写父类的成员时要声明为override
open
子类重写的成员默认是open
的,可以用final
禁止继续继承
open class Parent{
open var i:Int = 1
open fun foo(){}
fun bar(){}
}
open class Child : Parent() {
override var i: Int = 2
override final fun foo(){}
override fun bar(){} // error
}
抽象
用abstract
声明抽象类和函数
抽象类和函数默认是open
的
可以用抽象成员覆盖父类的非抽象开放成员
abstract class Animal {
abstract fun play()
}
class Dog : Animal() {
override fun play() {
}
}
接口
使用interface
定义接口
接口中的方法可以有默认实现
interface Inter{
fun go()
fun ok(){
println("ok")
}
}
class InterClass : Inter{
override fun go(){
}
}