4

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

4
  • It would be empty in the beginning, but you could add entries to Root.content. Commented Mar 11, 2019 at 19:44
  • 1
    I updated my question to use mutable collections. Commented Mar 11, 2019 at 19:52
  • 1
    Can you say what is your goal? Why do you need bi-directional references? Commented Mar 11, 2019 at 21:01
  • I would like e.g. to list all entries of a directory but would also like to print a parent directory of a file/directory. Commented Mar 11, 2019 at 21:08

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Seems reasonable. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.