Question

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.

Was it helpful?

Solution

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):

  1. 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...
  2. 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.
  3. 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.
  4. 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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top