黑猴子的家:Scala 包可见性

在Java中,没有被声明为public、private或protected的类成员,在包含该类的包中可见。在Scala中,你可以通过修饰符达到同样的效果。以下方法在它自己的包中可见

package com.nick.impatient.people
class Person {
 private[people] def description="人的名字:" + name
}

尖叫提示:private 不写,默认是private[this],表示当前包或类中,private[people]指定到包范围的访问权限

当然,也可以将可见度延展到上层包

private[impatient] def description="人的名字:" + name
package com.nick.impatient

class Cat{
 import com.nick.impatient.people.Person
 val person = new Person
 person.description
}

package people{
 class Person{
   private[impatient] def description = "人的名字:Nick"
 }

 class Dog{
   val person = new Person
   person.description
 }
}

转载于:https://www.jianshu.com/p/5050aa5132f0

猜你喜欢

转载自blog.csdn.net/weixin_34240657/article/details/91182487