2013-04-10 112 views
-1

我有一箇中斷點設置在線s = new Array(capacity),但它似乎沒有調用apply方法。我是否正確實施了它?申請方法不被稱爲

object StacksAndQueuesTest { 

    def main(args: Array[String]) { 

     val f = new FixedCapacityStackOfStrings(3) 
     println(f.isEmpty); 

    } 

} 

class FixedCapacityStackOfStrings(capacity : Int) { 

    var s : Array[String] = _ 
    var N : Int = 0 

    def isEmpty : Boolean = { 
    N == 0 
    } 

    def push(item : String) = { 
    this.N = N + 1 
    s(N) = item 
    } 

    def pop = { 
    this.N = N - 1 
    val item : String = s(N) 

    /** 
    * Setting this object to null so 
    * that JVM garbage collection can clean it up 
    */ 
    s(N) = null 
    item 
    } 

    object FixedCapacityStackOfStrings { 
    def apply(capacity : Int){ 
    s = new Array(capacity) 
    } 
} 

} 
+1

什麼是適用,甚至在做什麼? s甚至不存在於你的對象中。您是否嘗試使用apply創建FixedCapacityStackOfStrings的新實例? – vptheron 2013-04-10 20:23:56

+0

這是否編譯? 's'不在'object'的範圍內 - 它是'class'中的一個實例變量。 – 2013-04-10 20:24:53

+0

它正在編譯,因爲伴侶對象可以訪問伴侶類的字段。請參閱:http://stackoverflow.com/questions/11604320/whats-the-difference-between-a-class-with-a-companion-object-and-a-class-and-ob – Infinity 2013-04-10 20:35:04

回答

0

主叫對象'FixedCapacityStackOfStrings'來查看我需要使用的.isEmpty方法:

def apply(capacity: Int) : FixedCapacityStackOfStrings = { 
    new FixedCapacityStackOfStrings(capacity) 
    } 

代替

def apply(capacity: Int) { 
    new FixedCapacityStackOfStrings(capacity) 
    } 
+0

它是如何從我的答案差異? – 2013-04-22 12:35:35

+0

@TejaKantamneni your code'object FixedCapacityStackOfStrings {'should be'object FixedCapacityStackOfStrings = {'? – 2013-04-22 14:08:28

+0

嗯..根據我的理解,它不是強制性的,編譯器會自動推斷它(有一個「=」本身就足夠了) – 2013-04-22 15:18:05

2

在你的情況下,同伴的對象可能不是太大的幫助,除了避免new操作

class FixedCapacityStackOfStrings(capacity: Int) { 
    var s: Array[String] = new Array(capacity) 
    var N: Int = 0 

    def isEmpty: Boolean = { 
    N == 0 
    } 

    def push(item: String) = { 
    this.N = N + 1 
    s(N) = item 
    } 

    def pop = { 
    this.N = N - 1 
    val item: String = s(N) 

    /** 
    * Setting this object to null so 
    * that JVM garbage collection can clean it up 
    */ 
    s(N) = null 
    item 
    } 
} 

object FixedCapacityStackOfStrings { 
    def apply(capacity: Int) = { 
    println("Invoked apply()") 
    new FixedCapacityStackOfStrings(capacity) 
    } 

    def main(args: Array[String]){ 
    val f = FixedCapacityStackOfStrings(5) 
    println(f) 
    } 
} 

然後你就可以使用它像

val f = FixedCapacityStackOfStrings(5)

+0

謝謝,你是否嘗試過你的代碼,apply方法似乎沒有被調用? – 2013-04-10 20:31:58

+0

是的,請使用主要方法檢查更新的代碼 – 2013-04-10 20:34:42

+0

是的,它可以在我刪除新關鍵字時起作用,但是不應該也是這項工作? :val f = new FixedCapacityStackOfStrings(3) – 2013-04-10 20:37:50