Let's modify your code a bit, as it does not compile. When calling super.foo from B, you get an exception since it is not implemented.
package test
object HelloWorld1 {
trait A {
def foo(): Unit
}
trait B extends A {
override def foo(): Unit = {
println(getClass.getName)
// Can I determine the name of the concrete class here?
}
}
class C extends B { }
class D extends B { }
def main(args: Array[String]): Unit = {
val c = new C
c.foo()
val d = new D
d.foo()
}
}
Given that code, you can call getClass.getName which will provide a string, constructed from the full package name, and class of the current.
In the given example, you'll get:
test.HelloWorld1$C
test.HelloWorld1$D
If you take classes C and D, outside of HelloWorld1, you'll get:
C
D
If you want to get only C
and D
in the first option, i.e. inside HelloWorld1, you can call to getClass.getSimpleName
instead of getClass.getName
There is another option. You can also use getClass.getCanonicalName
which will replace the $
with .
.