I need access to the class of objects created in my own constructor (I do not think that for various reasons Relevant to my question).
I want something like this
class Foo (val i: int) class bar extends Foo (this.getClass.getName.length) val B = New to println (BI)
3 ("bar" length) to print. But it is not if the above code is inside any other object, then "this" refers to that object. If the above code is not within any other object (just in some packages), then the compiler complains with the error
: it can only be used in class, object or template class bar (This.getClass.getName) ^
Clarification: I can not change Fu to use a val in my body instead of its constructor because Fu's API is already present and Is fixed (yes, yes, i a construc Should be a parameter). It needs an integer logic at constructor time, but that integer can only be calculated to reach the orbit.
(I know that the above examples are still stupid and degenerate. If people take care, then I can explain in detail why I need a class in my real project), of course, During construction, the class of the object is known for compiler and runtime during creation. Syntax How do I get it? (Is there no such syntax? If not, I wonder if I am surprised that there is no ordinary, standard way to do this.)
You have to understand your motivation for the desire to do this. Should the name be a constructor parameter of Foo
or can it be an intangible member? Whether it should be a val
or what def
you can do it
square fu ( Val Name: String) Square Bar extends Foo ("") {override val name = getClass.getName}
and new bar (). Name
will give time
But I suspect that if your real motivation is known, then what you really want is a better way to do it.
Comments
Post a Comment