Scala: Difference between file.class and file$.class from scalac - scala

When I use scalac to compile file.scala, I end up with 2 outputs, file.class and file$.class. What is the difference between these files and which is the appropriate one to then run? I get distinctly different error messages between executing "scala file" vs "scala file$".

Scala objects get compiled to classes ending in "$" because you're allowed to have an "ordinary" class with the same name. But the object's methods are also exposed as static methods on the "ordinary" class, so that they can be called under the names you would expect. This is an artifact of trying to represent the scala semantics in a way that make sense to Java / the JVM, and I would encourage you to regard it as an implementation detail rather than something important.
(#MattPutnam's answer is correct that anonymous classes, including closures, are compiled to class files with $es in their name, but that's not what's causing your file$.class in this particular instance)
Use scala file. If you're interested in the implementation details you might also want to try java -cp /path/to/scala-library.jar file.

file$.class is some inner anonymous class. In Java they're very explicit, but they can be easy to miss in Scala. If you use any method that takes a function, there's an implicit anonymous class there. Post the code and I'll point it out.

Related

Compile only one class in a Scala program that contains more than one classes?

I know a Scala file, as in Java, should better define only one class. But now I have someone else's code. The code defines two classes. I 'd like to compile one of them because the other one does not compile. Of course I could have commented out the other one, but I have a large number of such files and I am looking for an automated solution for doing so. Any idea?
The Scala compiler works on whole files. The only way I can imagine doing this is to write a script which comments out all classes you don't want, runs scalac and then removes the comment markers again (well, you could also use Scala compiler as a library to get equivalent results without doing this literally). Needless to say, I don't think it's actually a good idea, but it's possible.

Renaming a .scala file in Scala IDE does not rename the class

When I rename a .scala file via Eclipse the class name itself is not renamed.
Is this expected behaviour? It does not seem to break anything.
I expect it to be renamed, coming from a Java background the filename/class name must equal each other.
correspondence between class name and file name is not required in scala.
You can (and usually do) define multiple types in each scala file.
The compiler will attempt to create a different .class file for each public type with the file name corresponding to the type name, for interoperability with java (for complex or nested types that don't have a direct correspondence in java, scalac will produce .class files with strange/mangled names...)
A few notes on why this correspondence is not enforced (probably not a complete list, but just to give you an idea):
it would be wasteful, given scala's terseness. case class Foo(foo:String) corresponds to a complete and somewhat sophisticated java class, but having it in its own file seems wasteful...
it would decrease code readability. Sometimes you define a hierarchy of case classes that correspond (for instance) to various messages you send to an actor. Having them together underlines their intent.
often it would be pointless. A relatively simple definition in scala, like trait Fooer {def foo="foo"} may be translated to various java-like types, that implement the "interface with a default implementation" nature of a trait. This gets worse for nested object/classes/types allowed by scala's syntax and used in some common scala patterns.
there are Scala semantics (sealed traits in particular) that actually require having multiple classes defined in a single file (credit to #DaveGriffith 's comment below)
In scala a .scala file can contain many (public) classes or packages.
The file name in scala does not have to match any of the class names in the file. You can have as many classes as you want in a scala file. The package structure also does not have to match the folder structure, although it is recommended to to be aligned.

class file optimization with the scala compiler

I have some class file inside a jar. Now I am searching for a way to optimize that class file using some components(most notably the Inliners) of the scala compiler.
My idea is to :
use the ICodeReader to emit ICode from class file
use an instance of the Inliner class in order to achieve the desired optimization
I am not know if that´s the right way to go
The problem is that
How to use the ICodeReader in order to read a class file and produce the needed ICode. ICodeReader inherits from ClassfileParser. The sole method that is for me more probable to use is parse(file: AbstractFile, root: Symbol) but the problem the root argument.
Any help is welcome
The Scala compiler acts on the source code and on the results of the intermediate step to produce bytecode, and will try to apply, if enabled, several optimisation.
In your case, if I understood right, you do not have the sources but the compiled classes, and I would not expect you being able to use a feature of Scala compiler on compiled classes.
What you should be looking to, in my understanding, is a bytecode optimizer , such as ProGuard, which is able to take existing bytecode and optimize it without having access to the source code
http://proguard.sourceforge.net/#FAQ.html

scala: analogy to metaclasses in python?

in scala i need to implement something similar to python metaclasses. in my case the goal of using the metaclasses is usually to create a registry of all the subclasses of a particular base class - that is, a mapping from say a string representation of the class to a reference to the class. in python it's very convenient to put a metaclass on the base class so that nothing special needs to be done on every subclass. i'm looking to do something similar in scala. is there any way to emulate metaclasses, or otherwise do this a different way? thanks!
If you know the fully qualified name of the class, you can load it using the usual Java reflection methods in java.lang.Class, namely Class.forName(String fqClassName). Given the resulting instance of Class, instantiation is easy only if there's a zero-argument constructor, otherwise you get entangled in the messy world of all the Java reflection types.
If you want a kind of "discovery" where classes unknown at compile time and whose names are not supplied as an input or parameter of the program in some way, then the classloader approach is probably the only answer.
There's nothing similar to python's metaclasses. The registry you speak of might be possible using custom class loaders or reflection.

Is there a method_missing in scala?

similar to the one in Ruby
Yes, as of Scala 2.9 with the -Xexperimental option, one can use the Dynamic trait
(scaladoc). Classes that extend Dynamic get the magical method applyDynamic(methodName, args) which behaves like Ruby's method_missing.
Among other things, the Dynamic trait can be useful for interfacing with dynamic languages on the JVM.
The following is no longer strictly true with the Dynamic trait found in [experimental] Scala 2.9. See the answer from Kipton Barros, for example.
However, Dynamic is still not quite like method_missing, but rather employs compiler magic to effectively rewrite method calls to "missing" methods, as determined statically, to a proxy (applyDynamic). It is the approach of statically-determining the "missing" methods that differentiates it from method_missing from a polymorphism viewpoint: one would need to try and dynamically forward (e.g. with reflection) methods to get true method_missing behavior. (Of course this can be avoided by avoiding sub-types :-)
No. Such a concept does not exist in Java or Scala.
Like Java, all the methods in Scala are 'bound' at compile time (this also determines what method is used for overloading, etc). If a program does compile, said method exists (or did according to the compiler), otherwise it does not. This is why you can get the NoSuchMethodError if you change a class definition without rebuilding all affected classes.
If you are just worried about trying to call a method on an object which conforms to a signature ("typed duck typing"), then perhaps you may be able to get away with structural typing. Structural typing in Scala is magical access over reflection -- thus it defers the 'binding' until runtime and a runtime error may be generated. Unlike method_missing this does not allow the target to handle the error, but it does allow the caller to (and the caller could theoretically call a defined methodMissing method on the target... but this is probably not the best way to approach Scala. Scala is not Ruby :-)
Not really. It doesn't make sense. Scala is a statically-typed language in which methods are bound at compile time; Ruby is a dynamically-typed language in which messages are passed to objects, and these messages are evaluated at runtime, which allows Ruby to handle messages that it doesn't directly respond to, à la method_missing.
You can mimic method_missing in a few ways in Scala, notably by using the Actors library, but it's not quite the same (or nearly as easy) as Ruby's method_missing.
No, this is not possible in Scala 2.8 and earlier.