Huy Vo Huy Vo - 1 year ago 107
Scala Question

Scala's parser combinator: parse an option

Say I have a parser like this:

trait PT {}

trait StatementPT extends PT{}


class LoopConditionPT(val operation: String, val variable: IdentPT, val condition: Option[(String,ExpressionPT)]) extends StatementPT { ... }

bug me for a day, I mean I can deal with
, but
? I wrote this
def loopCondition
but it always raises error:

def loopCondition: Parser[LoopConditionPT] = "some string" ~ var ~ opt(("TIL"|"WILE") ~ expression) ^^ {
case a ~ b ~ Some(c ~ d) => new LoopCondition(a, b, Option[(c, d)])
case a ~ b ~ None => new LoopCondition(a, b, Option[("None", -1)])

Can someone help me fixes the
? Thanks.

mAt mAt
Answer Source

[] are used for denoting types. When you want to create an Option - i.e. call Option.apply() - use parenthesis instead of square brackets. So instead of

new LoopCondition(a, b, Option[(c, d)])


new LoopCondition(a, b, Option((c, d)))

or you can use syntactic sugar for tuples and say

new LoopCondition(a, b, Option(c -> d))