method visibility

method  access modifier

  1. Object-private scope 只能this
  2. Private  this和其他instances
  3. Protected  subclasses 
  4. Package  this package scope 相当于java的默认friendly
  5. More package-level control
  6. Public

1  most restrictive access is to mark a method as “object-private.”

private[this] def isFoo = true

只对current instance available,Other instances of the same class不能access,即使是在同一个class中。

2   available to (a) the current class and (b) other instances of the current class,not available to subclasses

和java 的private一样。

3  available to subclasses

Java,protected methods can be accessed by other classes in the same package, but not in Scala.

4  private[packageName] syntax--available to all members of the current package

5   fine-grained level of access control:

6  any class can access

//example for fine-grained control level
package com.acme.coolapp.model {
    class Foo {
        private[model] def doX {}
        private[coolapp] def doY {}
        private[acme] def doZ {}
    }
}

import com.acme.coolapp.model._

package com.acme.coolapp.view {
    class Bar {
        val f = new Foo
        f.doX  // won't compile
        f.doY
        f.doZ
    }
}

package com.acme.common {
    class Bar {
        val f = new Foo
        f.doX  // won't compile
        f.doY  // won't compile
        f.doZ
    }
}

 REFERENCE https://alvinalexander.com/scala/how-to-control-scala-method-scope-object-private-package

posted on 2017-09-28 14:48  satyrs  阅读(134)  评论(0编辑  收藏  举报

导航