Scala project-wide static instructions - scala

I'm using a Java lib within my Scala project. I want to call a specific static method adjustLib of that lib as early as possible and for every possible starting point of an execution (e.g. before runing the "main" App and before executing tests) to achieve the desired behaviour.
One solution would be to place this statement at the very top of each class, that might be executed (applies for all classes extending App and for all tests).
However, if someone implements a new, executable class but forgets adjustLib, things might get weird.
Is there any chance to define an object or something similar, that executes this adjustLib statement in a "static" manner every time anything in the given project is executed?

Related

scala object extends app does not print anything

I am learning Scala and as part of the journey I had come across two different ways to write your scala class - one with a main method and other without the main method but by extending App (earlier Application is deprecated due to concurrency issues).
I am executing the scripts in Command Line via scala executable as scala <nameOfScript>.scala. I run Scala 2.11.7 in Windows.
I have no issues when running a scala script/class with a main method.
object ObjectWithMainMethod {
def main(args:Array[String]) = {
println("Object with a main() method executed..")
}
}
It produces the following output.
Object with a main() method executed..
But, I don't get the output with its counterpart, which is extending App trait but without the main method.
object AppWithoutMainMethod extends App {
println("AppWithout main() method executed")
}
When I run this scala script, it does not print anything. However, when I looked at the complied .class files via javap utility, I could see the PSVM (public static void main() method) inside.
Am I missing something? Any help on this will be highly appreciated.
If you run scala -help you'll see this comment:
A file argument will be run as a scala script unless it contains only
self-contained compilation units (classes and objects) and exactly one
runnable main method. In that case the file will be compiled and the
main method invoked. This provides a bridge between scripts and standard
scala source.
This explains exactly what you're seeing - the scala command is primarily meant to execute "scripts", or a series of expressions - for quick, interactive evaluation of code snippets. It only runs "applications" (i.e. objects with main method) as a "special case", because it makes sense users will try to use it this way. So:
When you run scala ObjectWithMainMethod.scala, the main method is identified and the command enters this "special case", figuring out that you probably meant for it to work that way
When you run scala AppwithoutMainMethod.scala, even though App has a main method, this isn't identified as the "special case" but just as a series of expressions, so the main method isn't invoked.
If you compile your classes into .class files and run them via java -cp <classpath> <class-name> command, the two will produce identical results.
The same thing works if I run the file without the .scala extension. I am not sure the reason behind this.
scala AppWithoutMainMethod
It produces the following output
AppWithout main() method executed

How to create a scala class based on user input?

I have a use case where I need to create a class based on user input.
For example, the user input could be : "(Int,fieldname1) : (String,fieldname2) : .. etc"
Then a class has to be created as follows at runtime
Class Some
{
Int fieldname1
String fieldname2
..so..on..
}
Is this something that Scala supports? Any help is really appreciated.
Your scenario doesn't seem to make sense. It's not so much an issue of runtime instantiation (the JVM can certainly do this with reflection). Really, what you're asking is to dynamically generate a class, which is only useful if your code makes use of it later on. But how can your code make use of it later on if you don't know what it looks like? For example, how would your later code know which fields it could reference?
No, not really.
The idea of a class is to define a type that can be checked at compile time. You see, creating it at runtime would somewhat contradict that.
You might want to store the user input in a different way, e.g. a map.
What are you trying to achieve by creating a class at runtime?
I think this makes sense, as long as you are using your "data model" in a generic manner.
Will this approach work here? Depends.
If your data coming from a file that is read at runtime but available at compile time, then you're in luck and type-safety will be maintained. In fact, you will have two options.
Split your project into two:
In the first run, read the file and write the new source
programmatically (as Strings, or better, with Treehugger).
In the second run, compile your generated class with the rest of your project and use it normally.
If #1 is too "manual", then use Macro Annotations. The idea here is that the main sub-project's compile time follows the macro sub-project's runtime. Therefore, if we provide the main sub-project with an "empty" class, members can be added to it dynamically at compile time using data that the macro sees at runtime. - To get started, Modify the macro to read from a file in this example
Else, if you're data are truly only knowable at runtime, then #Rob Starling's suggestion may work for you as it did me. I'll share my attempt if you want to be a guinea pig. For debugging, I've got an App.scala in there that shows how to pass strings to a runtime class generator and access it at runtime with Java reflection, even define a Scala type alias with it. So the question is, will your new dynamic class serve as a type-parameter in Slick, or fail to, as it sometimes does with other libraries?

Cucumber's AfterConfiguration can't access helper modules

I have a modular Sinatra app without a DB and in order to test memcache, I have some test files that need to be created and deleted on the file system. I would like to generate these files in an AfterConfiguration hook using some helper methods (which are in a module shared with rspec, which also needs to create/delete these files for testing). I only want to create them once at the start of Cucumber.
I do not seem to be able to access the helpers from within AfterConfiguration, which lives in "support/hooks.rb." The helpers are accessible from Cucumber's steps, so I know they have been loaded properly.
This previous post seems to have an answer: Want to load seed data before running cucumber
The second example in this answer seems to say my modules should be accessible to my AfterConfiguration block, but I get "undefined method `foo' for nil:NilClass" when attempting to call helper method "foo".
I can pull everything out into a rakefile and run it that way, but I'd like to know what I'm missing here.
After digging around in the code, it appears that AfterConfiguration not only runs before any features are loaded, but before World is instantiated. Running self.class inside of the AfterConfig block returns NilClass. Running self.class inside of any other hook, such as a Before, will return MyWorldName. In retrospect, this makes sense as every feature is run in a separate instance of World.
This is why helpers defined as instance methods (ie def method_name) are unknown. Changing my methods to module methods (ie def ModuleName.method_name) allows them to function, since they really are module methods anyway.

Executing Scala objects in Eclipse without a main method

I have an assignment to code several methods in Scala. The methods will be encapsulated in an object that has no main method. The professor gave us a JAR file that contains an interface (my object implements this interface) as well as a sort of pseudo test object that performs various assert statements against each of my functions. This object also does not contain a main method.
Now in Intellij I simply had to declare the dependency on the JAR in the classpath, and it runs fine. Eclipse is giving me trouble though because when I go to define a Scala application run configuration it specifically asks me to name the class that contains a main method, and there is no main method.
I am assuming that I might be choosing the wrong project type for this type of set up, but I am inexperienced with this and I would appreciate any advice you might have for running something like this in eclipse.
Thanks.
I would either:
just write an object with a main method which calls the test object, or
start a Scala interpreter in your project (from context menu, under Scala).
Preferring the first approach, because it's faster to repeat tests after a modification.

I get new javascript every GWT compile without changing java source

GWT compiles the Java source into Javascript, and names the files according to a hash of their contents. I'm getting a new set of files every compile, because the javascript contents are changing, even when I don't change the source at all.
The files are different for OBF and PRETTY output, but if I set it to DETAILED, they're no longer different every compile. In PRETTY, I can see that all/most of the differences between compiles are in the value parameters for typeId. For example, a funciton called initValues() is called with different values for it's typeId parameter.
In PRETTY mode, the differences you see are allocation of Java Classes to TypeIds. It's how GWT manages run time type checking. You'll notice a table at the bottom of each script essentially mapping each typeId to all compatible superclasses. This is how GWT can still throw ClassCastException in JavaScript (though you should run into this very rarely!).
In OBF mode, the differences are due to the allocation of minified function names.
In both cases, it's due to the order the compiler is processing the code. Some internal symbol tables might be using a non-ordered collection store symbols for processing. It can happen for lots of reasons.
As far as I know, GWT will compile a new version every time you compile it, this is a feature ;)
You can use ant to control it though, so that it only builds the GWT section of your application if it's actually changed:
http://wiki.shiftyjelly.com/index.php/GWT#Use_The_Power_of_Ant_to_Build_Changes_Only