Kotlin Reference (八) 可见性修饰符, data class,object Claz

来源:互联网 发布:观看仙侠学院 网络电影 编辑:程序博客网 时间:2024/05/23 02:00

KotLin 相关文档


官方在线Reference
kotlin-docs.pdf
Kotlin for android Developers 中文翻译
Kotlin开发工具集成,相关平台支持指南
Kotlin开源项目与Libraries
Kotlin开源项目、资源、书籍及课程搜索平台
Google’s sample projects written in Kotlin
Kotlin and Android

 

可见性修饰符(visibility modifiers)


Classes, objects, interfaces, constructors, functions, properties and their setters can have visibility modifiers.
Getters always have the same visibility as the property.
There are four visibility modifiers in Kotlin: private , protected , internal and public .
The default visibility, used if there is no explicit modifier, is public .

fun baz() {} //default public, it will be visible everywhereprivate class Bar {}  //private , it will only be visible inside the file containing the declarationinternal fun Bas() {} //internal , it is visible everywhere in the same module(an IntelliJ IDEA module; a Maven or Gradle project; a set of files compiled with one invocation of the Ant task)//protected class Bz  //protected is not available for top-level declarations.class Human {//or interface//    — private     // this class only visible//    — protected   // same as private + visible in subclasses too//    — internal    // 在module中 任何能访问该类的client//    — public      // 任何能访问该类的client}class C private constructor(a: Int) {} //the primary constructor visible this class onlyinternal class D /*internal or public*/ constructor(a: Int) {} //constructor: visible internalfun local() {//    public val c = 10    /*    Local variables, 不具有可见性修饰语     */}

 

使用data class声明class


data class 特性:

  1. 所有声明在主构造函数中的属性都会派生出相应的get/set(set需要属性为var)
    还会自动生成:

    equals() ,hashCode()
    toString() of the form “User(name=John, age=42)” ,
    copy() ,比如下面的 Human类的默认实现就是:fun copy(id: Int = this.id) = Human(id)

    如果类中实现或重写了某个函数后,那这个函数就不会再自动生成了()
     

  2. data class 声明时,前面不能有 abstract, open, sealed or inner

  3. 必须声明主构造函数,且至少有一个参数

data class 示例

open class Human(id: Int) {    override fun toString(): String {        return "Human"    }}data class User(val id: Int, val name: String, var age: Int): Human(id) {    var weight: Float = 0.0f    constructor(id: Int, weight: Float) : this(id, "", 18) {        this.weight = weight    }//    override fun toString(): String {//        return "User"//    }}

User继承了Human(id),主构造函数有三个参数,内部还定义了一个有两个参数的构造函数。

初始化:

var u = User(1, "stone", 28) //id=1, name="stone", age=28u = User(2, 1.0f) //id=2, name="", age=18u.copy()u.copy(2)u.copy(2, "stone2")u.copy(2, "stone2", 27)

对于自动生成的copy方法,会根据主构造函数的参数上,来生成。
会对每个参数给定默认值(即原对象属性的值),所以,调用时可以少传或不传参数

 

使用object声明class

—————
如下,使用object 声明一个ObjClass类:

object ObjClass {    const val const5 = 4    fun staticMethod() {}}

会成一个ObjClass的单例类,对于属性类似data class,会自动生成相应的getter、setter;成员的访问,类似java中的static形式;即[className].member