Why can this Kotlin Object Inherit from itself? - kotlin

I am trying to interface with TeamCity using Kotlin.
When you convert a project to Kotlin (from .xml) you will have a file called Project.kt which is where you can set all your configurations.
With no editing mine looks like this:
object Project : Project(/* Some Function Literal with Receiver */)
This looks like circular inheritance? There are imports that I am omitting, but surely that wouldn't make that big of a difference? Could the name be interpreted in different ways depending on where it appears in the file?
My mind is interpreting the object signature like this:
object = Object declaration for singleton.
Project (first occurrence) = Name of object.
: = Inheritance marker.
Project (second occurrence) = Base class to inherit from.
() = Constructor call to the base class.
Is this circular inheritance or have I missed something big about Kotlin? I have looked here and here and can't seem to find my answer.

Assuming qualified classes other.Project and my.Project, you'd have two different classes defined with the same name, in different packages.
Since my.Project is defined as a Singleton, you cannot extend from it and the actual base class is other.Project. Kotlin is clever enough to differentiate. If you would try to do the same with a class declaration, you'd get a circular inheritance.
You could even try to force extending from the Singleton explicitly, but then you'll have the error Cannot inherit from a Singleton. So basically this only works well if you imported the right classes.

Related

How to get only declared members (not inherited) with Kotlin Reflection?

Is there any way to get only the declared members of a class (not inherited) with Kotlin Reflection?
Something equivalent to getDeclaredMethods(), or ...Fields(), in Java, but for members and JVM free, which:
Returns an array containing Method objects reflecting all the declared methods of the class ... but excluding inherited methods.
Or like a binding flag, such as BindingFlags.DeclaredOnly of dotnet.
Because the reflection is based on the class, So the following is only for the kotlin/JVM, not suitable for the Kotlin/JS or Kotlin/Native.
For the Kotlin/JS it supports limit, for detail, you can see this
document
The only supported parts of the API are: (::class),KType and typeOf
Firstly, you can use the SomeClass::class.java.declaredMethods to get the
getDeclaredMethods. That is the java method. Because the Kotlin file after compiled it is still a class. so you can directly use it.
You can also add the kotlin reflect to get the KClass, then use the declaredFunctions to get. Here is the Document
Returns all functions declared in this class. If this is a Java class, it includes all non-static methods (both extensions and non-extensions) declared in the class and the superclasses, as well as static methods declared in the class
For how to get the KClass, you can use the following code
Class.forName("mypackage.MyClass").kotlin.declaredFunctions
Besides the method, the other property you can also get. such as
declaredMembers
Returns all functions and properties declared in this class. Does
not include members declared in supertypes.
allSuperclasses
functions
Returns all functions declared in this class, including all non-static methods declared in the class and the superclasses, as well as static methods declared in the class.
you can read the document using it.

If I imported a class, should I still prepend that class name to its methods when they're used in a different class?

I work with a codebase where there are many classes with thousands of lines of code. I've noticed inconsistencies in style concerning prepending class names when using their methods and I'm trying to figure out the previous developer's reasoning. If we
import GeneralCode
in Class A, is it bad practice to write
GeneralCode.DoSomething()
in Class A since we already imported it (instead of simply using DoSomething())? I would think so, but I suppose it's also nice to know which methods come from which classes at a glance, since Class A imports many classes and uses methods from several of them.
EDIT: This is for VB.NET, not Java (sorry for the wrong tag, rough morning). I am new to VB.NET but GeneralCode and DoSomething() are not declared as static, neither is the import in Class A.
Might be something to do with VB.NET, but DoSomething() can indeed be used with or without prepending GeneralCode.
A method need to be prefixed with
The class name if it's a static method.
The name of the instance when it's not a static method.
Unless you are calling a method from your own class.

difference between class and instance structure

I'm currently trying to learn how to use GObject and there's a point I absolutely don't understand: What's the difference between the class and the instance structure (like "MamanBarClass" and "MamanBar") resp. how do I use them? At the moment I'd put all my object attributes into a private structure (like "MamanBarPrivate"), register it with "g_type_class_add_private" and define properties/getters/setters to access them. But when I leave the class structure empty I get the following error at "g_type_register_static_simple":
specified class size for type `MamanBar' is smaller than `GTypeClass' size
And why are all object methods defined in the class structure (like "GtKWidgetClass")? Probably I'm just screwing up everything, but I only worked with Delphi for OOP yet (I know, nothing to be proud about :D)
Regards
I'm currently trying to learn how to use GObject and there's a point I absolutely don't understand: What's the difference between the class and the instance structure (like "MamanBarClass" and "MamanBar") resp. how do I use them?
The class structure is only created once, and is not instance-specific. It's where you put things which are not instance-specific, such as pointers for virtual methods (which is the most common use for the class struct).
At the moment I'd put all my object attributes into a private structure (like "MamanBarPrivate"), register it with "g_type_class_add_private" and define properties/getters/setters to access them.
Good. That's the right thing to do.
But when I leave the class structure empty I get the following error at "g_type_register_static_simple":
You should never leave the class structure empty. It should always contain the class structure for the type you're inheriting from. For example, if you're trying to create a GObject, the class structure should look like this (at a minimum):
struct _MamanBarClass {
GObjectClass parent_class;
};
Even if you're not inheriting from GObject, you still need the base class for GType:
struct _FooClass {
GTypeClass parent_class;
};
This is how simple inheritance is done in C.
And why are all object methods defined in the class structure (like "GtKWidgetClass")? Probably I'm just screwing up everything, but I only worked with Delphi for OOP yet (I know, nothing to be proud about :D)
Those are virtual public methods. As for why they're defined in the class structure instead of the instance structure, it's because the implementations are the same for every instance.

How do I create a file-scope class in objective-c?

I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.

What's wrong with Copy Constructors? Why use Cloneable interface?

When programming C++ we used to create copy constructors when needed (or so we were taught). When switching to Java a few years ago, I noticed that the Cloneable interface is now being used instead. C# followed the same route defining the ICloneable interface. It seems to me that cloning is part of the definition of OOP. But I wonder, why were these interfaces created, and the copy constructor seems to have been dropped?
When I thought about it, I came to the thought that a copy constructor would not be useful if one needs to make a copy of an object whose type is not known (as in having a reference to a base type). This seems logical. But I wonder whether there are other reasons that I do not know of, for which the Cloneable interfaces have been favored over copy constructors?
I think it's because there is no such inherent need for a copy constructor in Java and in C# for reference types. In C++ objects are named. You can (and you will most often) copy (and in C++1x move) them around e.g when returning from functions, since returning pointers require you to allocate dynamic memory which would be slow and painful to manage. The syntax is T(x) so it makes sense to make a constructor taking a T reference. C++ couldn't make a clone function, since that would require returning an object by value again (and thus another copy).
But in Java, objects are unnamed. There are only references to them, which can be copied, but the object itself isn't copied. For the cases when you actually need to copy them, you can use the clone call (but i read in other anwers clone is flawed. i'm no java programmer so i cannot comment that). Since not the object itself is returned, but rather a reference to it, a clone function will suffice. Also a clone function can be overriden. That's not going to work with copy constructors. And incidentally, in C++ when you need to copy a polymorphic object, a clone function is required too. It's got a name, the so-called virtual copy constructor.
Because C++ and Java (and C#) aren't the same thing. C++ has no built-in interfaces because interfaces aren't part of the language. You can fake them with abstract classes but they aren't how you think about C++. Also, in C++ assignment is normally deep.
In Java and C# assignment just involves copying the handle to the internal object. Basically when you see:
SomeClass x = new SomeClass();
in Java or C#, there's a level of indirection builtin that doesn't exist in C++. In C++, you write:
SomeClass* x = new SomeClass();
Assignment in C++ involves the dereferenced value:
*x = *another_x;
In Java you can get access to the "real" object as there is no dereference operator like *x. So to do a deep copy, you need a function: clone(). And both Java and C# wrapped that function into an interface.
It's the issues of final type and of cascading the clone operation through the super classes which is not addressed by copy constructors - they are not extensible. But the Java clone mechanism is widely considered badly broken too; especially problems where a subclass does not implement clone(), but inherits from a superclass that implements cloneable.
I strongly recommend you research cloning carefully, whatever path you choose - you will likely choose the clone() option, but make sure you know exactly how to do it properly. It's rather like equals() and hashCode() - looks simple on the surface, but it has to be done exactly right.
I think you haven't get the right point. I give you my two cents.
Fundamentally there's a problem: creating a clone of a class without knowing the exact class type. If you use copy constructor, you cannot.
Here is an example:
class A {
public A(A c) { aMember = c.aMember }
int aMember;
}
class B : A {
public B(B c) : base(c) { bMember = c.bMember }
int bMember;
}
class GenericContainer {
public GenericContainer(GenericContainer c) {
// XXX Wrong code: if aBaseClass is an instance of B, the cloned member won't
// be a B instance!
aBaseClass = new A(c.aBaseClass);
}
A aBaseClass;
}
The Clone method, if declare virtual, could create the right class instance of the generic member.
An this problem is common to every language, C# C++ or Java...
Maybe this is what you was meaning, but I cannot understand this from any answer.
Just wanted to add that in Java the copy constructor is not completely useless.
There are cases where your class has a private instance variable of a mutable non-final type, e.g. Date, and has a setter and getter for the variable. In the setter, you should make a copy of the given date, because the caller could modify it later and thereby manipulate your object's internal state (usually by accident, but maybe intentional). In the getter, the same precaution is required.
The defensive copy could be implemented by calling clone() (the class Date is cloneable), but a malicious caller could call the setter with a subclass of Date which overrides the clone() method with {return this;}, and so the caller might still be able to manipulate your object. This is where the copy constructor comes into play: By calling new Date(theDate), you are sure to get a fresh Date instance with the same timestamp as the given date, without any connection between the two date instances. In the getter, you could use the clone method, because you know the private variable will be of class Date, but for consistency, usually the copy constructor is used there, too.
Also note that the copy constructor would note be required if the Date class was final (calling clone() were safe) or immutable (no copy required).
I think its only because once u have defined a copy constructor, you could never pass the reference itself again. (Unless it would have a function that does that...but thats not any easier than using the clone() method.)
In C++ its not a problem: you can pass the whole object or its reference.