Kotlin - Dynamic Runtime Deconstructing in Kotlin - kotlin

Is it be possible to create a method in Kotlin 1.5 to support dynamic object creation at runtime and support deconstruction like so:
val (A, B, C, D, E) = buildNodes("A,B,C,D,E")
The difference here is that we would need to create the methods component1() .. component5() dynamically at runtime.
https://kotlinlang.org/docs/destructuring-declarations.html

There is one problem with this. componentX() functions are used not only to get the value at runtime. They are also used to infer the type of destructured variables. You can dynamically choose in buildNodes() what will be the value of A, but you can't decide on its compile type dynamically.
So it really depends on what do you mean that these items are constructed dynamically. You can create items dynamically as long as their types are somehow predictable. For example, if your buildNodes() always returns only strings, then this is fine. In fact, you can return List<String> and it will work for at most 5 items. You can also create an interface and decide on the implementation at runtime. Or even make buildNodes() generic, so it returns different types depending on something. At the last resort, you can return Any and check the type of destructured items at the runtime.
But you can't expect that depending on the contents of the passed string, the A variable will change its compile type.

Related

How to put class dynamically in <>

I know there are various capabilities in Java with reflection.
For example:
Class<?> clazz = Class.forName("java.util.Date");
Object ins = clazz.newInstance();
I wonder if I could pass class dynamicaly in some method declaration in <> tags (or there is other way to do it if it must be fixed). I would like to change that class declaration dynamicaly; because I would like to write generic method for all types of classes.
In there, I have this:
List<Country>
Can I write it something diffrent with reflection? For example can it be somehow be achieved to pass class as parameter (or how else should be this done):
List<ins>
? I would appreciate examples.
This cannot be done because generics are a compile time feature. Once code is compiled, the only place where generics are exists are at method signatures, and they are only used for compiling new code.
When working with reflection, you are basicly working with raw types, and need to code according to that, that means, you can cast the returned result of newInstance() to the list type your need, for example:
List<Country> ins = (List<Country>)clazz.newInstance();
This is a safe operation to do, because you know at that point its empty, and isn't passed to any outside code.
I don't think this is possible. Generics in Java are implemented in a way that prohibits runtime access.
Generics are there so that the compiler can verify correct typing, but are no longer present at runtime (this is called "type erasure"). Reflection deals with the runtime representation of types only. As far as I know the only case where reflection has to deal with generics is to find out "fixed" type parameters of sub-classes, e.g. when you have class Bar<T> and class Foo extends Bar<String>, you can find out that the T of Bar is fixed to String in Foo using reflection. However, this is information found in the class file, too. Except that, reflection can only see or create raw-types.

What's the difference between an object and a data object?

The other day I noticed that I sometimes put data in front of objects and other times not:
object A
data object B
What's the difference between an object and a data object?
The fact that data is allowed on an object declaration is in fact a bug (KT-6486) which should be fixed.
data is an annotation which causes the compiler to generate equals, hashCode, toString, copy and componentN functions. It doesn't make much sense when applied to an object declaration for two reasons:
An object declaration cannot have a constructor, and all these functions work based on properties defined in the primary constructor.
There's only one instance of any object at runtime.
So no componentN functions would be generated, copy can't work, and the generated equals/hashCode/toString implementations will be equivalent to the default ones from Any which are based on identity.

Frege: can I derive "Show" for a recursive type?

I'm trying to implement the classical tree structure in frege, which works nicely as long as I don't use "derive":
data Tree a = Node a (Tree a) (Tree a)
| Empty
derive Show Tree
gives me
realworld/chapter3/E_Recursive_Types.fr:7: kind error,
type constructor `Tree` has kind *->*, expected was *
Is this not supported or do I have to declare it differently?
Welcome to the world of type kinds!
You must give the full type of the items you want to show. Tree is not a type (kind *), but something that needs a type parameter to become one (kind * -> *).
Try
derive Show (Tree a)
Note that this is shorthand for
derive Show (Show a => Tree a)
which resembles the fact that, to show a tree, you need to also know how to show the values in the tree (at least, the code generated by derive will need to know this - of course, one could write an instance manually that prints just the shape of the tree and so would not need it).
Generally, the kind needed in instances for every type class is fixed. The error message tells you that you need kind * for Show.
EDIT: eliminate another possible misconception
Note that this has nothing to do with your type being recursive. Let's take, for example, the definition of optional values:
data Maybe a = Nothing | Just a
This type is not recursive, and yet we still cannot say:
derive Show Maybe -- same kind error as above!!
But, given the following type class:
class ListSource c -- things we can make a list from
toList :: c a -> [a]
we need say:
instance ListSource Maybe where
toList (Just x) = [x]
toList Nothing = []
(instanceand derive are equivalent for the sake of this discussion, both make instances, the difference being that derive generates the instance functions automatically for certain type classes.)
It is, admittedly, not obvious why it is this way in one case and differntly in the other. The key is, in every case the type of the class operation we want to use. For example, in class Show we have:
class Show s where
show :: s -> String
Now, we see that the so called class type variable s (which represents any future instantiated type expression) appears on its own on the left of the function array. This, of course, indicates that s must be a plain type (kind *), because we pass a value to show and every value has per definition a type of kind *. We can have values of types Int or Maybe Int or Tree String, but no value ever has a type Maybe or Tree.
On the other hand, in the definition of ListSource, the class type variable c is applied to some other type variable a in the type of toList, which also appears as list element type. From the latter, we can conclude, that a has kind * (because list elements are values). We know, that the type to the left and to the right of a function arrow must have kind * also, since functions take and return values. Therefore, c a has kind *. Thus, c alone is something that, when applied to a type of kind * yields a type of kind *. This is written * -> *.
This means, in plain english, when we want to make an instance for ListSource we need the type constructor of some "container" type that is parameterized with another type. Tree and Maybe would be possible here, but not Int.

What is Method, Property and Function?

Yeah, I'm struggling with that. I cannot distinguish among them because every explanation I read is so unclear and philosophical enough. Can someone clear up these definitions for me ? Thanks guys.
These definitions apply as much to procedural-programming as oop ? Thanks.
Over time, the way people use each of these terms has changed (and will likely keep changing), but here's what they probably mean if you're reading articles written in the last decade or so:
Functions (aka subroutines) are relatively self-contained, relatively independent pieces of code that make up a larger program.
Methods are functions attached to specific classes (or instances) in object-oriented programming.
Properties are an object-oriented idiom. The term describes a one or two functions (depending on the desired program behavior) - a 'getter' that retrieves a value and a 'setter' that sets a value. By convention, properties usually don't have many side-effects. (And the side-effects they do have usually have limited scope: they may validate the item being set, notify listeners of a change, or convert an object's private data to or from a publicly-declared type.)
Function is a combination of instructions coupled together to achieve some result. It may take arguments and return result. If a function doesn't return a result it is usually called a procedure. Examples:
function drawLine(x1, y1, x2, y2):
// draws a line using Bresenham's algorithm from x1,y1 to x2,y2.
// doesn't return anything
function <number> add(a, b):
// adds a to b and returns the result as a number
return a + b
So functions are to do some particular work. For example, when you need to draw a polygon of 3 lines as a part of a vector image it is more convenient to call drawLine thrice than to put all the routine for line drawing inline.
Methods ("member functions") are similar to functions, they belongs to classes or objects and usually expresses the verbs of the objects/class. For example, an object of type Window usually would have methods open and close which do corresponding operations to the object they belong.
Properties are as in everyday language and technically are fields of objects/classes with dedicated getter/setter routines (which can be considered as methods. There are languages that don't have properties and this behavior is achieved using a private field+get/set methods.).
Field - A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
Property - A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field.
Method - A method is a code block containing a series of statements. In C#, every executed instruction is done so in the context of a method.
Procedure - A procedure is a code block containing a series of statements.
Function - A function is a code block containing a series of statements. That return operation result.
Function is a standalone construction like trim(), strlen(), fopen() etc.
function myAbcFunction() { ... }
Method is a function of object. It is defined in class. Property is just property of object:
class MyClass {
public $property; // Public property: $objInstance->property
protected $property2; // Protected property
public function doSth() {
// That's a method. $objInstance->doSth();
}
}
I suggest read the manual Classes and Objects chapter.
In OOP the primary structure is an object.
Method is a named action which can be applied to the object.
Property is a named value, which the object has. For example, object Human has the property 'Age'.
function is a more general thing, than a method. It is just an action, that doesn't belong to any object. But method is a function that belongs to the object.
a)Function
Refers to block of statements that perform a particular task and return a value.
b)Procedure
Refers to the building blocks of a program that do not return a value when called.
c)Method
Refers to the action that object can perform.

Should private functions modify field variable, or use a return value?

I'm often running into the same trail of thought when I'm creating private methods, which application is to modify (usually initialize) an existing variable in scope of the class.
I can't decide which of the following two methods I prefer.
Lets say we have a class Test with a field variable x. Let it be an integer. How do you usually modify / initialize x ?
a) Modifying the field directly
private void initX(){
// Do something to determine x. Here its very simple.
x = 60;
}
b) Using a return value
private int initX(){
// Do something to determine x. Here its very simple.
return 60;
}
And in the constructor:
public Test(){
// a)
initX();
// b)
x = initX();
}
I like that its clear in b) which variable we are dealing with. But on the other hand, a) seems sufficient most of the time - the function name implies perfectly well what we are doing!
Which one do you prefer and why?
Thank for your answers guys! I'll make this a community wiki as I realize that there is no correct answer to this.
I usually prefer b), only I pick a different name, like computeX() in this case. A few reasons for why:
if I declare computeX() as protected, there is a simple way for a subclass to influent how it works, yet x itself can remain a private field;
I like to declare fields final if that's what they are; in this case a) is not an option since initialization has to happen in compiler (this is Java-specific, but your examples all look Java as well).
That said, I don't have a strong preference between the two methods. For instance, if I need to initialize several related fields at once, I will usually pick option a). That, though, only if I cannot or don't want for some reason, to initialize directly in constructor.
For initialization I prefer constructor initialization if it's possible,
public Test():x(val){...}, or write initialization code in the constructor body. Constructor is the best place to initialize all the fields (actually, it is the purpose of constructor). I'd use private initX() approach only if initialization code for X is too long (just for readability) and call this function from constructor. private int initX() in my opinion has nothing to do with initialization(unless you implement lazy initialization,but in this case it should return &int or const &int) , it is an accessor.
I would prefer option b), because you can make it a const function in languages that support it.
With option a), there is a temptation for new, lazy or just time-stressed developers to start adding little extra tasks into the initX method, instead of creating a new one.
Also, in b), you can remove initX() from the class definition, so consumers of the object don't even have to know it's there. For example, in C++.
In the header:
class Test {
private: int X;
public: Test();
...
}
In the CPP file:
static int initX() { return 60; }
Test::Test() {
X = initX();
}
Removing the init functions from the header file simplifies the class for the people that have to use it.
Neither?
I prefer to initialize in the constructor and only extract out an initialization method if I need a lot of fields initialized and/or need the ability to re-initialize at another point in the life time of an instance (without going through a destruct/construct).
More importantly, what does 60 mean?
If it is a meaningful value, make it a const with a meaningful name: NUMBER_OF_XXXXX, MINUTES_PER_HOUR, FIVE_DOZEN_APPLES, SPEED_LIMIT, ... regardless of how and where you subsequently use it (constructor, init method or getter function).
Making it a named constant makes the value re-useable in and of itself. And using a const is much more "findable", especially for more ubiquitous values (like 1 or -1) then using the actual value.
Only when you want to tie this const value to a specific class would it make sense to me to create a class const or var, or - it the language does not support those - a getter class function.
Another reason to make it a (virtual) getter function would be if descendant classes need the ability to start with a different initial value.
Edit (in response to comments):
For initializations that involve complex calculations I would also extract out a method to do the calculation. The choice of making that method a procedure that directly modifies the field value (a) or a function that returns the value it should be given (b), would be driven by the question whether or not the calculation would be needed at other times than "just the constructor".
If only needed at initialization in the constructor, I would prefer method (a).
If the calculation needs to be done at other times as well, I would opt for method (b) as it also makes it possible to assign the outcome to some other field or local variable and so can be used by descendants or other users of the class without affecting the inner state of the instance.
Actually only a) method behaves as expected (by analyzing method name). Method b) should be named 'return60' in your example or 'getXValue' in some more complicated one.
Both options are correct in my opinion. It all depeneds what was your intention when certain design was choosen. If your method has to do initialization only I would prefer a) beacuse it is simplier. In case x value is also used for something else somewhere in logic using b) option might lead to more consistent code.
You should also always write method names clearly and make those names corresponding with actual logic. (in this case method b) has confusing name).
#Frederik, if you use option b) and you have a LOT of field variables, the constructor will become a quite unwieldy block of code. Sometimes you just can't help but have lots and lots of member variables in a class (example: it's a domain object and it's data comes straight from a very wide table in the database). The most pragmatic approach would be to modularize the code as you need to.