AX - How to flush Macro from cache - macros

It seems AX Macro remains in cache
I had a macro defined in AOT and declared in classDeclaration
as I needed to change one of the values
I want to force all users to get the new value when they reopen AX
but user is still getting the old value of a Macro
Macro definition: TestMacro
#define.columnA(1)
//#define.columnC(3) // old value
#define.columnC(2) // new value
Class Declaration: TestClass
class TestClass
{
#TestMacro // Remove/save and re-add/save this declaration apparently solved
}
Attempted Solutions:
Deleting Usage Data related to TestClass (for all users): Failed
Removing and re-adding Macro from class declaration: Worked
Some other idea how to flush macro cache in AX?

As far as I know there is no cache specifically for macros, but an object cache that caches all AOT objects. You can flush this cache using Tools > Development tools > Application objects > Refresh Dictionary/AOD.
But your problem is not this object cache, but the compiled version of TestClass. During compilation the reference to TestMacro is replaced with the actual macro values. So even if you change the TestMacro, the compiled version of TestClass will still run with the old macro values. You have to recompile TestClass so that it will consider the changes in TestMacro.
In case your macro values are changing regularly, you should consider using a parameter table instead of a macro.

I don't think Macros are cached but are replaced during compile. Are you compiling only the method and not the entire class?

Related

Constructor.newInstance replaces Scala object

I was debugging a deserialization issue with Jackson where Scala object instances seemed to be replaced. I managed to drill the issue down to this code:
object WaitWhat extends App {
object XX
val x1 = XX
// Notice: no assignment!
XX.getClass.getConstructor().newInstance()
val x2 = XX
println(x1)
println(x2)
}
The output is:
WaitWhat$XX$#5315b42e
WaitWhat$XX$#2ef9b8bc
(Of course the actual hash codes change each run.)
IntelliJ's debugger also indicates that x1 and x2 really are different instances, despite the fact that the result of newInstance is completely ignored.
I would have expected a no-op, or an exception of some kind. How is it possible that the actual object instance gets replaced by this call?
Objects in Scala have a private constructor that can’t be called with new (since it’s private), but can still be called using reflection.
Under the hood, the object is accessed by static MODULE$ field. This field is the singleton instance created internally by calling the private constructor.
As long as you access the object in your Scala or in your Java code using MODULE$ you will be ok. However, you can't be sure, that some library won't create an additional instance of your object with a private constructor using reflection. In this case, whenever private constructor will be called, a new instance of the object will be created and reassigned to MODULE$.
This can happen especially if you use Java libraries, that are not aware of the existence of Scala objects.
Please check this article for more details.
Anyway, I would just create custom deserializer for Jackson (similarly to the solution described in the article).

How to get application "namespace" in Swift implicitly?

Short version:
Assuming I have an app called MyApp. In some situation I have a duplicate class name so that one is MyClass where the other is MyApp.MyClass. How can I call MyApp.MyClass having MyApp constant (do not need to change the code if I change the app name).
Why and what happened (long version):
So assume we are in this MyApp application having following code (the real one is way way longer and used allover the app):
class MyClass {
}
class SomeOtherClass {
class MyClass {
}
func findMyClass(fromMyClass: MyApp.MyClass) -> MyClass {
...
}
}
Because there are two classes called MyClass in inner scope we need to call MyApp.MyClass to get the outer one which is all good.
But it seems a bit silly when MyApp changes which is my case.
Why did it change? I actually added a new target by duplicating the original one because I wanted to have some extra and some different settings (pretty standard procedure). So I renamed the new one to have MyApp-dev where I then got an error Use of undeclared type 'MyApp'.
So is there a keyword that can replace MyApp?
My current solution is to define a typealias on file scope that is then used inside the class to replace MyApp. The problem is that the method is not private so the typealias may not be private either which means I just have an extra name defined globally in the project.
EDIT:
Also there is a setting in Xcode build settings called Product Module Name which may be overridden to explicit naming which fixes the issue. Still this not really a good general solution; I can see cases where you might reuse the same code in multiple modules (creating libraries) which has the same issue. This would still meant that code would need to be fixed for each of these modules.

In Scala; should I use the App trait?

I've just started learning Scala and many of the tutorials that I'm following are using a combination of different representations for a main method. Aside from the familiar main method; there's also the use of traits App or Application.
It appears that Application has been deprecated and is not recommended, but I can't find any information that explains much beyond this about each of these ways to define an entry point.
So, I'm wondering if someone could explain to me:
How do the traits App and Application work?
Why is the trait Application no longer recommended and what does the App trait do that is different?
Where should I use the traditional main method and when should I use App to start my program? What's the difference between the two approaches?
The problem with the Application trait is actually described in its documentation:
(1) Threaded code that references the object will block until static initialization is complete. However, because the entire execution of an object extending Application takes place during static initialization, concurrent code will always deadlock if it must synchronize with the enclosing object.
This is a tricky one. If you extend the Application trait, you are basically creating a Java class:
class MyApplication implements Application {
static {
// All code goes in here
}
}
The JVM runs the above class initializer implicitly synchronized on the MyApplication class. This way, it is assured that no instance of MyApplication is created before its class is initialized. If you spawn a thread from your application that again needs to access an instance of MyApplication, your application would dead lock as the class initialization is only complete after the entire program has executed. This implies a paradox as no instance can be created as long as your program is running.
(2) As described above, there is no way to obtain the command-line arguments because all code in body of an object extending Application is run as part of the static initialization which occurs before Application's main method even begins execution.
A class initializer does not take any arguments. Also, it is run first, before any values could be handed to the class as the class initializer needs to be executed before you could even assign a static field value. Thus, the args that you normally receive on a main method are lost.
(3) Static initializers are run only once during program execution, and JVM authors usually assume their execution to be relatively short. Therefore, certain JVM configurations may become confused, or simply fail to optimize or JIT the code in the body of an object extending Application. This can lead to a significant performance degradation.
The JVM optimizes code that is run frequently. This way, it makes sure that no run time is wasted on methods that are not really a performance bottle neck. However, it safely assumes that static methods are only executed once as they cannot be invoked manually. Thus, it will not optimize the code that is run from a class initializer which is however your application's main method code if you are using the Application trait.
The App trait fixes all this by extending DelayedInit. This trait is explicitly known to the Scala compiler such that initialization code is not run from a class initializer but from another method. Note the for name reference that is haded to the trait's only method:
trait Helper extends DelayedInit {
def delayedInit(body: => Unit) = {
println("dummy text, printed before initialization of C")
body
}
}
When implementing DelayedInit, the Scala compiler wraps any initialization code of its implementing class or object into a for name function which is then passed to the delayedInit method. No initialization code is executed directly. This way, you can also run code before an initializer is run what allows Scala for example to print an application's runtime metrics to the console which is wrapped around the program's entry point and exit. However, there are some caveats of this approach and using DelayedInit is therefore deprecated. You should really only rely on the App trait which solves the problems that are imposed by the Application trait. You should not implement DelayedInit directly.
You can still define a main method if you want to, as long as you define it in an object. This is mostly a matter of style:
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}

Why are classes inside Scala package objects dispreferred?

Starting with 2.10, -Xlint complains about classes defined inside of package objects. But why? Defining a class inside a package object should be exactly equivalent to defining the classes inside of a separate package with the same name, except a lot more convenient.
In my opinion, one of the serious design flaws in Scala is the inability to put anything other than a class-like entity (e.g. variable declarations, function definitions) at top level of a file. Instead, you're forced to put them into a separate ''package object'' (often in package.scala), separate from the rest of the code that they belong with and violating a basic programming rule which is that conceptually related code should be physically related as well. I don't see any reason why Scala can't conceptually allow anything at top level that it allows at lower levels, and anything non-class-like automatically gets placed into the package object, so that users never have to worry about it.
For example, in my case I have a util package, and under it I have a number of subpackages (util.io, util.text, util.time, util.os, util.math, util.distances, etc.) that group heterogeneous collections of functions, classes and sometimes variables that are semantically related. I currently store all the various functions, classes, etc. in a package object sitting in a file called io.scala or text.scala or whatever, in the util directory. This works great and it's very convenient because of the way functions and classes can be mixed, e.g. I can do something like:
package object math {
// Coordinates on a sphere
case class SphereCoord(lat: Double, long: Double) { ... }
// great-circle distance between two points
def spheredist(a: SphereCoord, b: SphereCoord) = ...
// Area of rectangle running along latitude/longitude lines
def rectArea(topleft: SphereCoord, botright: SphereCoord) = ...
// ...
// ...
// Exact-decimal functions
class DecimalInexactError extends Exception
// Format floating point value in decimal, error if can't do exactly
formatDecimalExactly(val num: Double) = ...
// ...
// ...
}
Without this, I would have to split the code up inconveniently according to fun vs. class rather than by semantics. The alternative, I suppose, is to put them in a normal object -- kind of defeating the purpose of having package objects in the first place.
But why? Defining a class inside a package object should be exactly equivalent to defining the classes inside of a separate package with the same name,
Precisely. The semantics are (currently) the same, so if you favor defining a class inside a package object, there should be a good reason. But the reality is that there is at least one good reason no to (keep reading).
except a lot more convenient
How is that more convenient?
If you are doing this:
package object mypkg {
class MyClass
}
You can just as well do the following:
package mypkg {
class MyClass
}
You'll even save a few characters in the process :)
Now, a good and concrete reason not to go overboard with package objects is that while packages are open, package objects are not.
A common scenario would be to have your code dispatched among several projects, with each project defining classes in the same package. No problem here.
On the other hand, a package object is (like any object) closed (as the spec puts it "There can be only one package object per package"). In other words,
you will only be able to define a package object in one of your projects.
If you attempt to define a package object for the same package in two distinct projects, bad things will happen, as you will effectively end up with two
distinct versions of the same JVM class (n our case you would end up with two "mypkg.class" files).
Depending on the cases you might end up with the compiler complaining that it cannot find something that you defined in the first version of your package object,
or get a "bad symbolic reference" error, or potentially even a runtime error. This is a general limitation of package objects, so you have to be aware of it.
In the case of defining classes inside a package object, the solution is simple: don't do it (given that you won't gain anything substantial compared to just defining the class as a top level).
For type aliase, vals and vars, we don't have such a luxuary, so in this case it is a matter of weighing whether the syntactic convenience (compared to defining them in an object) is worth it, and then take care not to define duplicate package objects.
I have not found a good answer to why this semantically equivalent operation would generate a lint warning. Methinks this is a lint bug. The only thing that I have found that must not be placed inside a package object (vs inside a plain package) is an object that implements main (or extends App).
Note that -Xlint also complains about implicit classes declared inside package objects, even though they cannot be declared at package scope. (See http://docs.scala-lang.org/overviews/core/implicit-classes.html for the rules on implicit classes.)
I figured out a trick that allows for all the benefits of package objects without the complaints about deprecation. In place of
package object foo {
...
}
you can do
protected class FooPackage {
...
}
package object foo extends FooPackage { }
Works the same but no complaint. Clear sign that the complaint itself is bogus.

With Scala closures, when do captured variables start to live on the JVM heap?

Related question:
Scala closures compared to Java innerclasses -> final VS var
I wonder when do Scala makes the variables captured into a closure live on the heap instead of the stack. I'm reading the Scala book of Martin Odersky but for now i didn't find this information. Can someone explain what's behind the hood?
An anonymous function (and actually, any function) in scala is actually an object (an instance of Function*). When it is instantiated, the capture of vals is done by copying the vals into internal fields of the function object. In the function body (that is, in the function object's apply method) the access to the captured vals is done by accessing these fields.
The capture of vars is similar, except that the compiler has to add a level of indirection: the var value is accessed through some hidden mutable holder (simply an object with a mutable field pointing to the current value of the var) and this is this holder that is copied into the function object. When writing into the var (either by local code or by the function object), it is the holder's field which is written. This mechanism ensures that the local code and function's code manipulate the same data, and both see each other's modifications.
So the answer is that a captured vals and a captured var both always live on the heap (whether directly as a field of the function object, or as a field of some wrapper object)
I don't know the insides of the compiler, but here is how it can be done. For each local variable, the compiler maintains a flag initialized to false. Whenever the variable is used, the compiler checks whether it is being used inside a class or closure that doesn't contain the variable's declaration; if so the flag is set to true. At the end of the variable's scope, if the flag is still false, the variable can live on the stack. Otherwise it must live on the heap.