Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with type name clashes in Scala?

Tags:

scope

scala

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?

like image 482
r0estir0bbe Avatar asked Dec 02 '25 12:12

r0estir0bbe


1 Answers

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}.
like image 151
mpilquist Avatar answered Dec 04 '25 05:12

mpilquist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!