Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
user701254 Avatar asked Dec 09 '22 18:12

user701254


1 Answers

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)
like image 52
Paolo Falabella Avatar answered Mar 06 '23 21:03

Paolo Falabella