Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any means in Scala to split a class code into many files?

Tags:

scala

netbeans

There are 2 reasons for me to ask:
1. I'd like a better code fragmentation to facilitate version control on per-function level
2. I struggle from some attention deficit disorder and it is hard for me to work with long pieces of code such as big class files

To address these problems I used to use include directives in C++ and partial class definitions and manually-definable foldable regions in C#. Are there any such things available in Scala 2.8?

I've tried to use editor-fold tag in NetBeans IDE, but it does not work in Scala editor unfortunately :-(

UPDATE: As far as I understand, there are no such facilities in Scala. So I'd like to ask: someone who has any connection to Scala authors, or an account on their Bugzilla (or whatever they use), please, suggest them an idea - they should probably think of introducing something of such (I was fascinated by C# regions and partial classes for example, and plain old includes also look like a convenient tool to have) to make Scala even more beautiful through laconicity, IMHO.

like image 385
Ivan Avatar asked Sep 15 '10 19:09

Ivan


3 Answers

How about doing it with traits? You define it like this:

trait Similarity 
{
  def isSimilar(x: Any): Boolean
  def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}

...and then you use it like so:

class Point(xc: Int, yc: Int) extends Similarity 
{
 var x: Int = xc
 var y: Int = yc
 def isSimilar(obj: Any) =
    obj.isInstanceOf[Point] &&
    obj.asInstanceOf[Point].x == x
}

If the class Point were bigger, you could split it further into traits, resulting in the division that you want. Please note, however, that I don't think this is advisable, as it will make it very difficult to get a good overview of your code, unless you already know it by heart. If you can break it in a nice way, however, you might be able to get some nice, reusable blocks out of it, so in the end it might still be worth doing.

Best of luck to you!

like image 133
Mia Clarke Avatar answered Oct 15 '22 05:10

Mia Clarke


//file A.scala
trait A { self: B =>
....
}

//file B.scala
trait B { self: A =>
....
}

//file C.scala
class C extends A with B
like image 5
Mushtaq Ahmed Avatar answered Oct 15 '22 03:10

Mushtaq Ahmed


I suggest to read white paper by Martin at this link. In this white paper 'Case Sudy: The Scala Compiler' chapter will give you idea about how you can achieve component based design having code in several separate files.

like image 4
Jaydeep Patel Avatar answered Oct 15 '22 05:10

Jaydeep Patel