Note that there are some explanatory texts on larger screens.

plurals
  1. POModify a class with typed traits in Scala
    text
    copied!<p>I've been playing around with Scala recently, and when working with parser combinators, I kind of had some problems extending them. Basically, what I'm trying to do is something like this.</p> <pre><code>import scala.util.parsing.combinator.RegexParsers abstract class Statement case object Foo extends Statement case object Bar extends Statement case object Baz extends Statement class Program(statements: List[Statement]) class FooBarLanguageParser extends RegexParsers { def program: Parser[Program] = rep(statement) ^^ (v =&gt; new Program(List() ++ v)) def statement: Parser[Statement] = foo|bar def foo: Parser[Statement] = "foo" ^^ (_ =&gt; Foo) def bar: Parser[Statement] = "bar" ^^ (_ =&gt; Bar) } trait BazStatement { this: FooBarLanguageParser =&gt; override def statement: Parser[Statement] = baz|this.statement // inifinite recursion def baz: Parser[Statement] = "baz" ^^ (_ =&gt; Baz) } object Main { def main(args: Array[String]) { val normalFooBar = new FooBarLanguageParser() val fooBarProgram = normalFooBar.parseAll(normalFooBar.program, "foo bar") val extendedFooBar = new FooBarLanguageParser() with BazStatement val extendedFooBarProgram = extendedFooBar.parseAll(extendedFooBar.program, "foo bar baz") println(fooBarProgram.successful) println(extendedFooBarProgram.successful) } } </code></pre> <p>Here, I would like to call <code>FooBarLanguageParser</code>'s <code>statement</code> method in <code>BazStatement</code>, but with the above code I'm recursively calling <code>BazStatement</code>'s method, so no way it would work properly.</p> <p>I already took a look at the answers around, and I know that I could extend the class and use abstract override, or somethink like this, but I don't think it would really make any sense here, as <code>BazStatement</code> is really an additional feature I want to mixin with my basic parser. I definitely don't want to have some random things like </p> <pre><code>object StrangeInheritance extends BazStatement </code></pre> <p>authorized in the code.</p> <p>Would there be any idiomatic way to do this properly in Scala or do I need to think again about the general design of the app?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload