I am playing with Scala. What I need is just a brunch of function definitions, but in Eclipse I can only create .scala files for which a function def must be inside an object or class.
But I see a Scala script online, here, which does not use an object to wrap all the functions.
It is of course ok for me to use an object to wrap all my functions, but I am just wondering whether it is required. Thanks!
But I see a Scala script online, here, which does not use an object to wrap all the functions.
Note that in this case, the functions can't be called from other files (they are wrapped in an object with compiler-generated name when run). If you "need just a brunch of function definitions", this is likely not what you want :) AFAIK, Scala IDE doesn't support script files at the moment, but you could log a feature request here.
Yes, in Eclipse you need to wrap everything in an object or a class.
You can edit Scala scripts in Eclipse as long as you wrap the code in an object and avoid the Shebang. Just run the script with scala -i scriptName.scala -e "Main.main(args)" (providing you have the "bin" folder of scala distribution on your path).
foo.scala:
object Main extends App {
println ("foo")
}
To run it:
scala -i foo.scala -e "Main.main(args)"
To my knowledge it isn't possible to write functions or variables completely outside of scope. That said it is possible to write them outside of class/object definitions. You just have to wrap them in a package object. What's happening is basically that instead of tying the function/variable to a given class or object, you tie it to a package. Example:
package test
package object inside {
def hello = println("Hello from outer space!")
class Foo {
hello // call the function from the package
}
}
Now, when you construct Foo, you should get printed "Hello from outer space!".
Without knowing completely what I'm talking about, I could imagine that the script version you mentioned above works, because the script is being run in some kind of an environment. So imagine some class loading the script, then wrapping it into an object and the running it. That would imply a situation somewhat like the one above: the functions still "belong" to somewhere.
Related
Is there any way to find classes/objects that extend a certain class in sbt in the sources?
I played around with https://github.com/ruippeixotog/sbt-classfinder but that is only good for Compile and Test it seems.
What I intend to do is:
Find all classes that extends StyleSheet.Standalone (from
https://github.com/japgolly/scalacss/)
"Compile" (*) (object.render[TypedTag[String]] them and put the output in a specific folder
(*) Actually I want to invoke the render method on each of them and put the output (a string) into a x.css file.
I believe that sbt-classfinder does exactly what you have asked for. If you want more from this question, you will need to be more specific about why it didn't work for you or what you want that it does not provide.
You said:
I want to invoke the render method on each [class that extends StyleSheet.Standalone] and put the output (a string) into a x.css file.
The first example in the sbt-classfinder README shows how to find a class "marked with the annotation QuickRun" and execute it, which is fairly close to that and should get you started..
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
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?
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 have a directory with some helper functions that should be put into a package. Step one is obviously naming the directory something like +mypackage\ so I can call functions with mypackage.somefunction. The problem is, some functions depend on one another, and apparently MATLAB requires package functions to call functions in the very same package still by explicitly stating the package name, so I'd have to rewrite all function calls. Even worse, should I decide to rename the package, all function calls would have to be rewritten as well. These functions don't even work correctly anymore when I cd into the directory as soon as its name starts with a +.
Is there an easier solution than rewriting a lot? Or at least something self-referential like import this.* to facilitate future package renaming?
edit I noticed the same goes for classes and static methods, which is why I put the self-referential part into this separate question.
In truth, I don't know that you should really be renaming your packages often. It seems to me that the whole idea behind a package in MATLAB is to organize a set of related functions and classes into a single collection that you could easily use or distribute as a "toolbox" without having to worry about name collisions.
As such, placing functions and classes into packages is like a final step that you perform to make a nice polished collection of tools, so you really shouldn't have much reason to rename your packages. Furthermore, you should only have to go through once prepending the package name to package function calls.
... (pausing to think if what I'm about to suggest is a good idea ;) ) ...
However, if you really want to avoid having to go through your package and prepend your function calls with a new package name, one approach would be to use the function mfilename to get the full file path for the currently running package function, parse the path string to find the parent package directories (which start with "+"), then pass the result to the import function to import the parent packages. You could even place these steps in a separate function packagename (requiring that you also use the function evalin):
function name = packagename
% Get full path of calling function:
callerPath = evalin('caller', 'mfilename(''fullpath'')');
% Parse the path string to get package directories:
name = regexp(callerPath, '\+(\w)+', 'tokens');
% Format the output:
name = strcat([name{:}], [repmat({'.'}, 1, numel(name)-1) {''}]);
name = [name{:}];
end
And you could then place this at the very beginning of your package functions to automatically have them include their parent package namespace:
import([packagename '.*']);
Is this a good idea? Well, I'm not sure what the computational impacts will be if you're doing this every time you call a package function. Also, if you have packages nested within packages you will get output from packagename that looks like this:
'mainpack.subpack.subsubpack'
And the call to import will only include the immediate parent package subsubpack. If you also want to include the other parent packages, you would have to sequentially remove the last package from the above string and import the remainder of the string.
In short, this isn't a very clean solution, but it is possible to make your package a little easier to rename in this way. However, I would still suggest that it's better to view the creation of a package as a final step in the process of creating a core set of tools, in which case renaming should be an unlikely scenario and prepending package function calls with the package name would only have to be done once.
I have been exploring answers to the same question and I have found that combining package with private folders can allow most or all of the code to be used without modification.
Say you have
+mypackage\intfc1.m
+mypackage\intfc2.m
+mypackage\private\foo1.m
+mypackage\private\foo2.m
+mypackage\private\foo3.m
Then from intfc1, foo1, foo2, and foo3 are all reachable without any package qualifiers or import statements, and foo1, foo2, and foo3 can also call each other without any package qualifiers or import statements. If foo1, foo2, or foo3 needs to call intfc1 or intfc2, then that needs qualification as mypackage.intfc1 or an import statement.
In the case that you have a large set of mutually interdependent functions and a small number of entry points, this reduces the burden of adding qualifiers or import statements.
To go even further, you could create new wrapper functions at the package level with the same name as private functions
+mypackage\foo1.m <--- new interface layer wraps private foo1
+mypackage\private\foo1.m <--- original function
where for example +mypackage\foo1.m might be:
function answer = foo1(some_parameter)
answer = foo1(some_parameter); % calls private function, not itself
end
This way, unlike the intfc1 example above, all the private code can run without modification. In particular there is no need for package qualifiers when calling any other function, regardless of whether it is exposed by a wrapper at the package level.
With this configuration, all functions including the package-level wrappers are oblivious of the package name, so renaming the package is nothing more than renaming the folder.