如何处理 Scala 中的类型名称冲突? [英] How to deal with type name clashes in Scala?

查看:42
本文介绍了如何处理 Scala 中的类型名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个从 Scanners 扩展的类,它迫使我定义类型 Token:

I'm writing a class that extends from Scanners which forces me to define the type Token:

object MyScanner extends Scanners {
  type Token = ...
}

问题是我的令牌类本身被称为Token:

The problem is that my token class itself is called Token:

abstract class Token(...)
case class Literal(...)
...

是否可以在 Scala 中以某种方式将 Scanners 的类型 Token 定义到我的 Token 类?

Is it in Scala somehow possible to define the type Token of Scanners to my Token class?

type Token = Token 显然不行.

我也试过像这样使用整个包名(以 main.scala 开头):

I also tried using the whole package name (which begins with main.scala) like this:

type Token = main.scala....Token

这是另一个名称冲突,因为我在 MyScanner 中定义了一个 main 函数.

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?

推荐答案

使用完全限定的类名定义令牌类型有效.为了避免名称与您的主方法发生冲突,您可以使用 root 前缀来指示您引用的是完全限定的类型名称,而不是相对类型名称或方法名称.例如:

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. 在 MyScanner 对象之外(在封闭对象中或在包对象中)定义类型别名.
  2. 导入您的令牌类并将其别名作为导入的一部分.例如:import main.scala.{Token =>MyToken}.

这篇关于如何处理 Scala 中的类型名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆