Android

[WIP]Kotlin 可见范围

2018-07-06  本文已影响4人  假装在去天使之城的路上

Visibility Modifiers
https://kotlinlang.org/docs/reference/visibility-modifiers.html

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.

Packages

Functions, properties and classes, objects and interfaces can be declared on the "top-level", i.e. directly inside a package:

// file name: example.kt
package foo

private fun foo() {} // visible inside example.kt

public var bar: Int = 5 // property is visible everywhere
    private set         // setter is visible only in example.kt
    
internal val baz = 6    // visible inside the same module

Classes and Interfaces

For members declared inside a class:

open class Outer {
    private val a = 1
    protected open val b = 2
    internal val c = 3
    val d = 4  // public by default
    
    protected class Nested {
        public val e: Int = 5
    }
}

class Subclass : Outer() {
    // a is not visible
    // b, c and d are visible
    // Nested and e are visible

    override val b = 5   // 'b' is protected
}

class Unrelated(o: Outer) {
    // o.a, o.b are not visible
    // o.c and o.d are visible (same module)
    // Outer.Nested is not visible, and Nested::e is not visible either 
}

Constructors

To specify a visibility of the primary constructor of a class, use the following syntax (note that you need to add an explicit constructor keyword):

class C private constructor(a: Int) { ... }

Local declarations

Local variables, functions and classes can not have visibility modifiers.

上一篇 下一篇

猜你喜欢

热点阅读