Extending an existing data structure in Scala

I have a normal tree defined in Scala.

sealed abstract class Tree
object Tree {
  case class Node (...) extends Tree
  case class Leaf (...) extends Tree
}

Now I want to add a member variable to all nodes and leaves in the tree. Is this possible with the extend keyword, or do I need to change the tree classes by adding [T]?

Update:
It seems that my question was misinterpreted. An example should clear it:

I need this tree structure (actually something more complex) has two doubles in the same context. In another context, I need it to have one line. And yet in another context, I need a clean tree without any (additional) members. And I would like the first two options to be the third option. Pseudocode:

DTree extends Tree with Touple2[Double, Double]
object DTree {
  case class Node (...) extends Tree.Node with Touple2[Double, Double]
  case class Leaf (...) extends Tree.Leaf with Touple2[Double, Double]
}

STree extends Tree with String
object DTree {
  case class Node (...) extends Tree.Node with String
  case class Leaf (...) extends Tree.Leaf with String
}

...

def f (t : Tree) { ... }

I want f to be able to process all trees.

+3
4

, , . , - , . , . - .

sealed abstract class Tree

trait TypedTree {
  type T
  val value:T
}

, , :

trait DTree extends TypedTree {
  type T = Touple2[Double, Double]
}
object DTree {
  case class Node (...) extends Tree.Node with DTree 
  case class Leaf (...) extends Tree.Leaf with DTree 
}

trait STree extends TypedTree {
  type T = String
}
object DTree {
  case class Node (...) extends Tree.Node with STree
  case class Leaf (...) extends Tree.Leaf with STree
}

. , - , .

+2

, Node/Leaf:


abstract class ExtraMember[T](member:T) extends Tree

, Node , , .

0

( ), abstract class Tree:

abstract
class Tree(te1: String, te2: Int)

case
class Node(...)
extends Tree(te1Arg, te2Arg)

.. , extends .

0

(), , Tree ( ), Tree.

, . , :

sealed abstract class Tree(prop1: String, prop2: Int)

case class Node(prop1: String, prop2: Int) extends Tree(prop1, prop2)

vals/vars . , , , :

sealed abstract class Tree {
  def prop1 : String
  def prop2 : Int
}

case class Node(a:String, b:Int) extends Tree {
  lazy val prop1 = "[" + a + "]"
  lazy val prop2 = b + 42
}

lazy vals , - , . , Scala , .

, :

sealed abstract class Tree

trait TreeExtras {
  def prop1 : String
  def prop2 : Int
}

case class Node(a:String, b:Int) extends Tree with TreeExtras {
  lazy val prop1 = "[" + a + "]"
  lazy val prop2 = b + 42
}

.., .

0

Source: https://habr.com/ru/post/1744667/


All Articles