How to deal with type name clashes in Scala?

孤者浪人 提交于 2019-12-22 09:59:22

问题


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:

  1. Defining a type alias outside of the MyScanner object (either in an enclosing object or in a package object).
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!