2011-10-10 46 views
1

例如,假设我有在斯卡拉,是否有任何机制继承本地方法变量?

class Parent { 

    def method() { 
     var myvar = "test" 
    } 

} 

是否有子类中访问MYVAR任何机制?

编辑:

我试图建立在现有的语言建模的DSL。这种语言具有的功能,如

onTrade { 
    if (price == ...) // will compile 
} 

onDayStart { 
    if (price == ...) // will not compile 
} 

这是因为如果价格是一个全局变量,但也有编译时检查,以确保它只是在正确的上下文中使用。我想一种方法来模拟这将是有局部变量,可以在子类中重写。喜欢的东西

// Parent 
onTrade { 
    var price = ... 
} 

// Child 
onTrade { 
    if (price == ...) 
    if (somethingelse == ...) // will not compile 
} 
+5

哇!为什么会有?这听起来像一个*糟糕的*功能! –

+3

告诉我们你想做什么。我们会告诉你如何以Scala的方式来做到这一点。 – missingfaktor

回答

3

您的问题可能的解决方法(虽然我不明白的方式来摆脱new):

// parent 
var onTrades = List[OnTrade]() 
class OnTrade { 
    var price = ... 
    ... 
    onTrades = this :: onTrades 
} 

// child 
new OnTrade { 
    if (price == ...) {...} // subclass constructor, will call OnTrade constructor first 
} 
9

不是真的。这是你的范围。如果你想让它在不同层次上可见,你应该改变变量本身的范围。

例如,如果您想要在类级别定义它,可以通过这种方式进行分享。如果局部变量实际上不是本地的,那么局部变量就不是本地变量。

范围是嵌套的,从最广泛到最本地。 Chapter 2, pg. 16 of the Scala Language Reference涵盖了“标识符,名称和范围”,更详细地解释了这一点。