When to put () on upper class and when not? - kotlin

This is Kotlin but in other languages, I have this question.
When we put sub class in super class or when we call members in class, I see sometimes people put () on that parent class and sometimes not.
Outer.Nested().foo()
Outer().Nested().foo()
what makes some have () and some not?

In the Kotlin docs, these are the key sentences:
A nested class marked as inner can access the members of its outer class. Inner classes carry a reference to an object of an outer class:
Without inner, the nested class is basically just a code organizational tool: the Nested class is its own, independent class. Other than the Outer.Nested notation (and things like functional visibility), the instances of the two classes are essentially unrelated.
But with inner, each Nested instance can see its Outer's instance members. To do that, it needs to know which instance of Outer. That means that each inner Nested instance needs to be created within the context of a specific Outer instance. That's what Outer() is doing. You could have also done:
val oObj = Outer()
val iObj = oObj.Inner() // "iObj" carries a reference to "oObj"

Related

How to mimic simple inheritance with base and child class constructors in Lua (Tutorial)

How to mimic simple inheritance with parent and child class constructors in Lua?
I will provide and accept and answer and would greatly appreciate if you commented on it or edited interesting information into it.
This is a guide for mimicking basic parent/child class inheritance in Lua.
I assume that basic features and syntax of Lua are known to the reader. The following statements are especially important:
There are no classes or objects in Lua, just tables.
A table can have a metatable.
If the metatable mt of a table t contains the __index metamethod (thus mt.__index), access to a non-existent key in t is attempted to be resolved via what's assigned to mt.__index.
If t calls a function t.foo() like this t:foo() then t itself is passed to foo() as the first argument called self. Inside the function, t itself is accessible as self.
Base class
Code
Base = {}
function Base:new(name)
Base.__index = Base
local obj = {}
setmetatable(obj, Base)
obj.name = name
return obj
end
function Base:sayName()
print(self.name..": My name is "..self.name..".")
end
Because of what the function Base:new(name) does, Base can now be seen as a new class, with Base:new(name) being its constructor. Remember that Base really is a table that sits somewhere in memory, not some abstract "class blue print". It contains a function Base:sayName(). This is what we could call a method with respect to OOP lingo.
But how does Base:new(name) let Base act like a class?
Explanation
Base.__index = Base
The Base table gets an __index metamethod, namely itself. Whenever Base is used as a metatable, searches to a non-existent index will be redirected to... Base itself. (Wait for it.) The line could also be written as self.__index = self, because Base calls :new(name) and thus self is Base therein. I prefer the first version, because it clearly shows what's happening. Also, Base.__index = Base could go outside of Base:new(name), however, I prefer having all the "set up" happen inside one scope (the "constructor") for the sake of clarity.
local obj = {}
setmetatable(obj, Base)
obj is created as a new empty table. It will become what we think of as an object of the "class" Base. The Base is now the metatable of obj. Since Base has an __index, access to non-existent keys in obj well be redirected to what is assigned to Base.__index. And since Base.__index is Base itself, access to non-existent keys in obj will be redirected to Base (where it would find Base:sayName(), for instance)!
obj.name = name
return obj
The obj (!) gets a new entry, a member, to which the constructor parameter is assigned. The obj is then returned and is what we would interpret as an object of class Base.
Demonstration
b = Base:new("Mr. Base")
b:sayName()
This prints "Mr. Base: My name is Mr. Base." as expected. b finds sayName() via the metatable-__index mechanism as described above, because it doesn't have such a key. sayName() lives inside Base (the "class table") and name inside b (the "object table").
Child class
Code
Child = {}
function Child:new(name, age) -- our child class takes a second argument
Child.__index = Child
setmetatable(Child, {__index = Base}) -- this is different!
local obj = Base:new(name, age) -- this is different!
setmetatable(obj, Child)
obj.age = age
return obj
end
function Child:sayAge()
print(self.name..": I am "..tonumber(self.age).." years old.")
end
The code is almost exactly the same as for the base class! Adding a second parameter in the Child:new(name, age) (i.e. the constructor) is not especially noteworthy. Base could also have had more than one parameter. However, the second and third line inside Child:new(name, age) were added and that is what causes Child to "inherit" from Base.
Note that Base may contain Base.__index, which makes it useful when used as a metatable, but that it has no metatable itself.
Explanation
setmetatable(Child, {__index = Base})
In this line, we assign a metatable to the Child class table. This metatable contains an __index metamethod, which is set to the Base class table. Thus, the Child class table will try to resolve access to non-existent keys via the Base class table. Thus, the Child class table has access to all of its own and all of Base's methods!
local obj = Base:new(name, age)
setmetatable(obj, Child)
In the first line, a new Base object table is created. At this point, its __index metamethod points to the Base class table. However, right in line two, its metatable is assigned to the Child class table. The reason why obj does not lose access to Base class methods lies in the fact that we redirected non-successful key accesses in Child to Base (by giving Child the proper metatable) just before! Since obj was created as a Base object table, it contains all of its members. Additionally, it also contains the members of a Child object table (once they are added in the Child:new(name, age) "constructor". It finds the methods of the Child class table via its own metamethod. And it finds the methods in the Base class table via the metamethod in the Child class table.
Note: With "Base object table" I mean the table that is returned by Base:new(name). With "Base class table" I mean the actual Base table. Remember, there are no classes/objects in Lua! The Base class table and the Base object table together mimic what we think of as OOP behavior. The same goes for Child, of course.
Also, scoping the assignment of Child's metatable inside Child:new(name, age) allows us to call Base's "constructor" and pass the name argument to it!
Demonstration
c = Child:new("Mrs. Child", 42)
c:sayName()
c:sayAge()
This prints "Mrs. Child: My name is Mrs. Child." and "Mrs. Child: I am 42 years old." as expected.
Conclusion
The sections above described how to implement OOP behavior in Lua. It is important to understand that
Base methods live inside the Base class table
Base members live inside the Base object table returned by Base:new()
Child methods live inside the Child class table
Child members live inside the Child object table returned by Child:new()
Referencing the correct tables is accomplished by the table's metatables.
All class tables assign themselves to their __index key. When used as metatables, they refer to themselves (i.e. where the class methods live). There is only one class table per "class".
Base classes don't have a metatable. They are used as metatables.
Child class tables also have a metatable, namely {__index = Base} (which redirects calls to the Base class table, i.e. where the Base class methods live).
All object tables assign their corresponding class tables as metatables. Since the class tables have set their __index metamethod, calls to the object tables can be redirected to the class tables where the class methods live. If it is a child class table (which means it also has a metatable), the redirection can happen even further. There can be arbitrarily many object tables.
Use the image above to follow along: What happens if a Child object table c tries to access a Base method, e.g. c:sayName()? Well: Has c a sayName() key? No. Does it have a metatable? Yes: Child (the Child class table). Does Child have an __index metamethod? Yes. Where does it point? To Child itself. Does Child have a sayName() key? No. Does Child have a metatable? Yes. Does it have an __index metamethod? Yes. Where does it point? To the Base class table. Does it have a sayName() key? Yes! :-)
Note
I am no Lua expert! I have only done some scripting in Lua so far, but over the last days I tried to wrap my mind around this. I found a lot of different, sometimes confusing solutions and finally arrived at this, which I would call the most simple but transparent solution. If you find any errors or caveats do not hesitate to comment!

Why data classes in Kotlin cannot be marked with inner modifier?

I have a simple class let's say User. Now I want to create an inner data class let's say UserProperty inside User class, but as soon as I add inner modifier to data class UserProperty the IDE complains about Modifier inner is incompatible with data. What am I missing?
On the one hand, inner classes use the outer instance as a hidden first constructor parameter (which is effectively private val). On the other, data class behavior exposes all constructor parameters, including their names (in toString()), so they "should be" visible. Plus, in this case
If a supertype has the componentN() functions that are open and return compatible types, the corresponding functions are generated for the data class and override those of the supertype. If the functions of the supertype cannot be overridden due to incompatible signatures or being final, an error is reported;
should component1() be the outer instance or the first parameter you actually wrote?
The designers likely decided any behavior would be surprising to enough users that it's better to disallow this at all. And if you want your UserProperty to be like an inner class, just add a User constructor parameter yourself.
An inner class instance is dependent on the existence of an outer class instance i.e You cannot have an instance of the inner class without the outer one.
Now, if you try to store this object in the DB, the 'data' modifier declares the inner object as an own instance to be stored, with violates the constraints of an inner class.
If that would be possible, you could extract the information of the inner class without having the outer one on your stack, which is by definition invalid.
Therefore, you can only apply the 'data' modifier on the outer class.. it should store the inner class as well (have to check this). if you need the inner class independent in your DB, it should be an own class in the first place.

In Kotlin, why can't I access the outer class on an instance of an inner class?

Why can't I access the outer class's properties on an instance of an inner class?
class A(val id: String) {
inner class B {}
}
fun test() {
val a = A("test")
val b = a.B()
aid(a)
bid(b)
}
fun aid(a:A): String = a.id
fun bid(b:A.B): String = b.id //Unresolved reference: id
In this example, b.id fails to compile.
I gather that I have to add a getter on B that returns this#A.id. But why?
An inner class just has a reference to the enclosing instance, and therefore does not inherit the outer class's members.
As inner classes have a reference to the enclosing class, this enclosing instance can be accessed within the class only (Java: Outer.this, Kotlin: this#Outer), but you are correct that you cannot access the enclosing instance from outside the inner class.
A class may be marked as inner to be able to access members of outer class.
Kotlin Reference / Nested and Inner Classes
Making your own getter function to return the enclosing instance is the only way to do this.
Though the generated reference to the outer instance is package-private according to Jon Skeet, neither Java nor Kotlin has any method of obtaining this instance. You can use reflection, but as the generated field name is possibly unreliable, your best choice is to modify the inner class.

when to use/make companion object?

So I'm new to Scala (and have almost zero java experience). I thought I understood OOP, in abstract, but disregard that. My question -- in a similar vein to "method name qualification when using a companion object" -- is about when a Scala pro would think to implement a class - companion object pattern?
From the question referenced above, it's not clear that companion objects were intended to store methods for the class's "internal use" (e.g. the poster wanted to use ^, defined in the object, inside /, defined in the class). So, I don't want to think of companion objects as "containers" for methods the companion class can use, because that's clearly not true...
I'm sorry if this is a vague question: I just want to know the correct way to use these guys.
Companion objects are useful for what you would use static methods for in Java...
One very common use is to define an apply() method in the companion object, which gives users the ability to use MyObject(arg, arg) as shorthand for new MyObject(arg, arg).
Companion objects are also a good place to put things like implicit defs.
I recently have been using companion objects in my akka apps as places to put message case classes which are specific to a supervisor actor and its children, but that I don't necessarily want code outside that subsystem to use directly.
Here's a simple example:
class Complex(real:Double, imag:Double) {
def +(that:Complex):Complex = Complex(this.real + that.real, this.imag + that.imag)
// other useful methods
}
// the companion object
object Complex {
def apply(real:Double, imag:Double) = new Complex(real, imag)
val i = Complex(0, 1)
implicit def fromInt(i:Int) = Complex(i, 0)
}
The normal OOP way to instantiate a new Complex object would be new Complex(x, i). In my companion object, I defined the function apply, to give us a syntactic sugar that allows us to write Complex(x, i). apply is a special function name which is invoked whenever you call an object directly as if it were a function (i.e., Complex()).
I also have a value called i which evaluates to Complex(0, 1), which gives me a shorthand for using the common complex number i.
This could be accomplished in Java using a static method like:
public static Complex i() {
return new Complex(0, 1);
}
The companion object essentially gives you a namespace attached to your class name which is not specific to a particular instance of your class.

Purpose of an Inner Class?

I was reading some posts and noticed samples with an inner class. I've been seeing it a lot lately, particularly in a few examples on MSDN that I was browsing through. I've never had to use an inner class before (but maybe I really should be) so I wonder what exactly is the point? I assume that an inner class (at least a private one anyways) is only available to the main class itself, so wouldn't it be the same to simply incorporate whatever functionality the inner class has into some methods of the outer class? Is there an OO reason behind the inner class?
I'm thinking mainly within C#, but I suppose that this could apply to any OO language that supports an inner class.
Take this sample on msdn for example: CharacterCollection and WordCollection are public classes within the Document class. What difference would there be if these were outside of the Document class?
Inner classes are very useful if they only pertain to their containing (or, outer) class.
A good example of a private inner class is when you need to manage something within the outer class that will never be exposed. In the example below, a cache manager handles caching and uncaching of objects. It uses a private inner class to store the pointer to an object that it wants to cache, and also the time it was last accessed. Code that users this hypothetical CacheManager need never know about CacheEntry.
class CacheManager
{
private:
class CacheEntry
{
private:
Object* m_pObjectToCache;
int m_nTicksSinceTouched;
}; // eo class CacheEntry
std::map<int, CacheEntry*> m_Cache;
public:
Object* getObject(int _id);
}; // eo class CacheManager
Then comes the case for a public inner class. I would use a nested class if the name (which I would like to keep simple), my conflict elsewhere:
class Tree
{
public:
// public class.. Node might pertain to anything in the code, let's keep it simple
// and clear that THIS Node belongs and works with THIS Tree class.
class Node
{
};// eo class Node
}; // eo class Tree
One reason is that inner classes have access to the members of the enclosing class directly. They do not need a reference to the enclosing class in order to access those members. At the same time other objects may need access to the inner object.
I can think of the example of Iterators that are declared as inner classes in collections. The iterator needs to have intimate knowledge of the collection that it iterates but the client code needs access to the iterator itself as an object. You cannot take the functionality of the iterator and include it in the outer class.
Maybe the responsibilities of the outer class does not include those of the inner class directly. So creating the inner class helps to maintain highly cohesive classes.