Kotlin学习笔记:类和函数

  1. 定义:class关键字

    你只需要在 类名后面写上它的参数。如果这个类没有任何内容可以省略大括号

    class Person(name : String , surname : String)

  2. 类继承:默认任何类都继承自Any类,默认所有类都不可以继承,需要用关键字open/abstract修饰class;继承使用符号:

    
    class Person(name : String , surname : String) : Animal(name : String)

函数

  1. 关键字:fun

  2. 默认返回值:Unit


fun add(x : Int , y : Int) : Int{
  return x+y
}
  1. 如果返回的结果可以使用一个表达式计算出来,你可以不使用括号而是使用等 号


fun add(x : Int , y : Int) : Int = x + y

构造方法和函数参数

  1. 函数参数:先写参数的名字再写它的类型

  2. 可以给参数指定默认值使其变得可选,在调用函数时第二个参数可以传或者不传

    fun toast(message : String , length : Int = Toast.LENGTH_SHORT){
      Toast.makeText(this,message,length)
    }
    
    toast("Hello")
    toast("Hello",Toast.LENTH_LONG)

猜你喜欢

转载自blog.csdn.net/chrissen/article/details/79885320