0

There is already In Scala, how do I get the *name* of an `object` (not an instance of a class)? but I have the following code:

package test

object A {
  object B {
    object C
  }
}

val tmp = A.B.C

I would like to get the string "A.B.C" from value tmp at runtime, so no package name and no $ since this is the same name used in pattern matching for the type.

I tried the following:

tmp.getClass.getSimpleName // leads to exception "Malformed class name"
tmp.getClass.getName // has package name and $ characters
tmp.getClass.getTypeName // the same
msg.getClass.getName.replace("$", ".") // we still have the package name

I want to get the exact same name as in the AST for pattern matching:

case A.B.C =>

Note that neither the package name nor the object names are fixed.

Baradé
  • 1,290
  • 1
  • 15
  • 35

2 Answers2

0

we still have the package name

So remove it:

val cls = tmp.getClass
cls.getName.stripPrefix(cls.getPackage.getName + ".").stripSuffix("$").replace("$", ".")

(the suffix is because it's an object)

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0
package whatever.however 

import scala.util.matching.Regex

object O {
  object A {
    object B {
      object C
      object D
    }
  }

  def relativeType2String(a: Any): String = {
    s"^${ Regex.quote(this.getClass.getName)}(\\.|\\$$)?(.*?)(\\$$)?$$".r.replaceFirstIn(a.getClass.getName, "$2").replace('$', '.')
  }

  // println(typeStringRelativeToHere(tmp))
}


object Run extends App {
  val tmp = O.A.B.C
  println(O.relativeType2String(tmp))

  // or match on type  
  import O._
  def onType(t: Any) = t match {
    case A.B.C => println("it's A.B.C")
    case A.B.D => println("it's A.B.D")
  }
  val tmp2 = A.B.D
  onType(tmp)
  onType(tmp2)
}

outputs

[info] A.B.C                                                                                                                                                                                                                
[info] it's A.B.C                                                                                                                                                                                                           
[info] it's A.B.D  

~
~

Volty De Qua
  • 199
  • 6