2012-04-18 51 views
3

我與同伴目標代碼和定義構造函數爲私有:斯卡拉私有訪問修飾符範圍

class Person private[Person] (var age: Int, var name: String) { 
    private[Person] def this(name: String) = this(0, name) 
} 

private class Employee(age: Int, name: String) extends Person(age, name) 

private class Worker(age: Int, name: String) extends Person(age, name) 

object Person { 
    def prettyPrint(p: Person) = println("name:%s age:%s".format(p.name, p.age)) 
    def apply(age: Int, name: String) = new Person(age, name) 
    def apply() = new Person(0, "undefined") 
    def apply(age: Int, name: String, personType: String): Person = { 
    if (personType == "worker") new Worker(age, name) 
    else if (personType == "employee") new Employee(age, name) 
    else new Person(age, name) 
    } 

} 

我的問題是,爲什麼在同一個包裝的另一個對象還可以訪問這一私有的構造函數。我添加了私人[這個],所以其他人無法訪問它,但也沒有同伴。我可以只有類和伴侶對象的私有屬性嗎?

+0

是不是因爲構造函數是由類調用的,所以它是正確的。也許你應該創建一個返回結果類的私有函數。 – 2012-04-18 15:02:53

+0

@Lukasz在你的例子中,'private'修飾符適用於構造函數,而不適用於屬性。你真的想限制調用構造函數還是隻有私人領域? – paradigmatic 2012-04-18 15:59:37

+2

'私人類員工(年齡:國際,名稱:字符串)擴展人(年齡,名稱)'slay在2.9.1編譯器。恭喜! – 2012-04-18 19:05:44

回答

1

此代碼不能編譯。 EmployeeWorker都嘗試訪問私有構造函數,並正確拒絕訪問。

你的問題提到一個私有變量,但沒有變量聲明爲私有變量。

因此,您的示例不完整,或者不正確。請更正例子,以便我們回答問題。

+0

謝謝我累了,我的意思是構造函數當然:) – Lukasz 2012-04-23 21:30:11

+0

好吧,所以問題是編譯器的bug,阻止它完成,所以我在Eclipse中看起來確定,而它沒有根本不會編譯。 – Lukasz 2012-04-23 21:31:12