开发者

In Scala, is there any mechanism for inheriting local method variables?

开发者 https://www.devze.com 2023-04-11 19:06 出处:网络
For example suppose I have class Parent { def method() { var myvar = \"test\" } } Is there any mechanism for accessing myvar in child classes?

For example suppose I have

class Parent {

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

} 

Is there any mechanism for accessing myvar in child classes?

Edit:

I'm trying to build a DSL modeled upon an existing language. That language has features such as

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

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

It is as if price is a global variable but there are compile time checks to make sure it is only used in the correct context. I was thinking one way to simulate this would be to have local variables that could be overridden in subclasses. Something like

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

// Chi开发者_运维知识库ld
onTrade {
    if (price == ...)
    if (somethingelse == ...) // will not compile
}


Not really. That's scope for you. If you want it to be visible at different levels, you should probably change the scope of the variable itself.

For example, if you want to define it at the class level, you can share it that way. Local variables wouldn't be local if they weren't actually, well, local.

Scopes are nested, from the most broad, to the most local. Chapter 2, pg. 16 of the Scala Language Reference covers "Identifiers, Names, and Scopes" which explains this in more technical detail.


Possible solution for your problem (though I don't see a way to get rid of 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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号