简体   繁体   中英

scala type mismatch error with sealed trait

I'm working on my very first scala project that is implementing a recursive descent math expression parser.

As in any recursive descent parser, I have function (corresponding to my grammar's procedures) that can return either Success with the rest of the line to parse and the result or Failure.

For that, I'm using two case class in a sealed trait so that my function can return a type Result corresponding to either a success or a failure but I'm having trouble getting that to compile and work. (I keep getting a type mismatch error in the match)

Any idea of what I'm doing wrong ?

Here his the code:

sealed trait Result
case class Success(expr: String, result: Int) extends Result
case object Failure extends Result

class PackratParser() {
   var x: Int = 3

   def pExpr(expr: String) : Result = {
       return Success(32)
   }

   def parseExpr(expr: String) : Int = {
       val p = pExpr(expr)
       p match {
           case Success(expr, res) => println("success!" + expr + res)
           case Failure => println("failure...")
       }
   }
}

Thanks :)

There are two issues. First, within pExpr , you're only providing a single parameter to Success even though it requires two:

   def pExpr(expr: String) : Result = {
       return Success(32) // Requires String and Int
   }

Second, the return type of parseExpr is Int , but you're currently not returning anything. It's up to you how you want to handle it, but one option would be to return an Option[Int] instead of an Int since you won't have an Int to return in the case of a Failure :

 def parseExpr(expr: String): Option[Int] = {
    val p = pExpr(expr)
    val maybeInt = p match {
      case Success(expr, res) => {
        println("success!" + expr + res)
        Some(res)
      }
      case Failure => {
        println("failure...")
        None
      }
    }
    maybeInt
  }

Working fiddle here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM