Search code examples
scalascala-3

Workarounds for a global / local naming conflicts


Say I have these two classes:

class A {
  def foo(i: String) = println(s"${i}")
  def foo(i: String, j: Int) = println(s"${i} ${j}")
}

class B {
  def foo(i: Int) = println(s"${i}")
  def foo(i: Int, j: String) = println(s"${i} ${j}")
}

I have the variable with the same name as a global variable and as a method in a class:

val inst = A()

abstract class AppB extends App { 
  def inst = B()
}

I extend the above:

object MyApp extends AppB {
  // Should reference A
  inst.foo("s11")
  inst.foo("s22", 11)
  
  // Should reference B
  inst.foo(33)
  inst.foo(44, "s33")
}

Assuming I do not want to rename, is there a way to:

  • Reference the global val inst?
  • "Shadow" def inst somehow, so that I can only use the global val inst one?

Solution

  • From https://dotty.epfl.ch/docs/reference/dropped-features/package-objects.html:

    If a source file src.scala contains such top-level definitions, they will be put in a synthetic object named src$package

    Maybe using the "auto-generated" object name to access val inst can work in this case?