Reputation: 3191
What would be the appropriate way to implement a file system class structure in scala?
I want the Root
to be a Directory
and to have itself as a parent.
import scala.collection.mutable
sealed trait Entry
class Directory(val parent: Directory, val content: mutable.IndexedSeq[Entry]) extends Entry
class File(val parent: Directory, val content: String) extends Entry
object Root extends Directory(Root, mutable.IndexedSeq[Entry]())
The attempt above results in:
Error:
(23, 31) super constructor cannot be passed a self reference unless parameter is declared by-name object Root extends Directory(Root, IndexedSeq())
Upvotes: 4
Views: 286
Reputation: 51271
One thing you could do is create a 2nd trait just for directories.
import scala.collection.mutable.ArrayBuffer // easier to update
sealed trait Entry
sealed trait Directory extends Entry {
val parent :Directory
val content :ArrayBuffer[Entry]
}
class File(val parent :Directory
,val content :String) extends Entry
class SubDir(val parent :Directory
,val content :ArrayBuffer[Entry]) extends Directory
object Root extends Directory {
override val parent :Directory = this
override val content :ArrayBuffer[Entry] = ArrayBuffer()
}
Now you can create/update directory contents, and the parent of Root
is still Root
.
Root.content += new File(Root, "name")
Root.content += new SubDir(Root, ArrayBuffer())
Root.parent.parent.parent //res2: Directory = Root$@294c7935
Upvotes: 1