Class X accepts type parameters

After reading this informative, well-written article about Parser Combinators , I see this code:

class DisParser[+A](left: Parser[A], right: Parser[A]) extends Parser[A] { def apply(s: Stream[Character]) = left(s) match { case res: Success => res case _: Failure => right(s) } } 

When I try to compile this code, I get:

 Parser.scala:19: error: class Success takes type parameters case res: Success => res ^ one error found 

Given the signature of Parser :

 case class Success[+A](value: A, rem: Stream[Character]) extends Result[A] 

How to change the case res: Success => res to give Success correct type parameter?

+6
source share
2 answers

What Success are you using? This ( Success from the Parsers package) or this ( Success from the user)? Both have type parameters, so you will need to specify

 res @ Success(_, _) => 

otherwise, you will have to deal with a wipe warning.

+6
source

Your parser should return a value of type Result[A] , as its type definition says (basically the parser is a function from character streams to the result of parsing) .:

 trait Parser[+A] extends (Stream[Character]=>Result[A]) 

So, you have two options:

 case res@Success (_,_) => res 

This is a match for the case class returned.

 case res:Success[_] => res.asInstanceOf[Success[A]] 

It matches the return type (using the instanceof operation). This is why you should use (you cannot match a type parameter without typetag value, since the JVM really erases the styles).

Both are valid in your case, in the first case you omitted the type parameter (this was your original error). In your attempt to follow @wheaties advice, you made a syntax error somewhere in your code, but this is really the best way to go here.

+2
source

Source: https://habr.com/ru/post/958786/


All Articles