问题
I'm writing a class that extends from Scanners which forces me to define the type Token:
object MyScanner extends Scanners {
type Token = ...
}
The problem is that my token class itself is called Token:
abstract class Token(...)
case class Literal(...)
...
Is it in Scala somehow possible to define the type Token of Scanners to my Token class?
type Token = Token obviously doesn't work.
I also tried using the whole package name (which begins with main.scala) like this:
type Token = main.scala....Token
This is another name clash as I have defined a main function inside MyScanner.
My current solution is to rename my token class. Is there another one where I can keep the initial name?
回答1:
Defining the Token type using a fully qualified class name works. To avoid the name clash with your main method, you can use the root prefix to indicate that you are referring to a fully qualified type name, not a relative type name nor a method name. For example:
package main
import scala.util.parsing.combinator.lexical._
case class Token(s: String)
object MyScanner extends Scanners {
type Token = _root_.main.Token
val Token = _root_.main.Token
def errorToken(msg: String) = Token(msg)
def token = ???
def whitespace = ???
def main = ???
}
Some other alternatives include:
- Defining a type alias outside of the MyScanner object (either in an enclosing object or in a package object).
- Importing your token class and aliasing it as part of import. For example:
import main.scala.{Token => MyToken}.
来源:https://stackoverflow.com/questions/15453247/how-to-deal-with-type-name-clashes-in-scala