How do I create a parent-child relationship in immutable Kotlin classes

How do I create a parent-child relationship in immutable Kotlin classes

Content Index :

How do I create a parent-child relationship in immutable Kotlin classes
Tag : kotlin , By : user92243
Date : November 28 2020, 08:01 AM

Any of those help I have immutable classes representing a tree, where the children need a parent reference. , You could try with a root node and builder params:
sealed class Node {
    data class Root(
        val createChildren: ParentList.() -> Unit
    ) : Node() {
        val children: List<Node> = ParentList(this).apply(createChildren)

    data class Branch(
        val createChildren: ParentList.() -> Unit,
        val parent: Node
    ) : Node() {
        val children: List<Node> = ParentList(this).apply(createChildren)

    data class Leaf(
        val parent: Node
    ) : Node()

class ParentList(
    val parent: Node,
    private val children: MutableList<Node> = mutableListOf()
) : List<Node> by children {

    fun branch(createChildren: ParentList.() -> Unit) {
        children += Node.Branch(createChildren, parent)

    fun leaf() {
        children += Node.Leaf(parent)


fun root(createChildren: ParentList.() -> Unit) = Node.Root(createChildren)
fun usage() {

    val graph = root {
        branch {
        branch {
            branch {
val Node.children: List<Node> get() = when(this) {
    is Node.Root -> children
    is Node.Branch -> children
    is Node.Leaf -> emptyList()

val Node.parent: Node? get() = when(this) {
    is Node.Root -> null
    is Node.Branch -> parent
    is Node.Leaf -> parent
fun Node.allChildren(): List<Node> = 
  children + children.flatMap { it.allChildren() }
fun Node.allParents(): List<Node> = 
  listOfNotNull(parent).flatMap { listOf(it) + allParents() }
fun Node.allChildren(): Sequence<Node> = 
  children.asSequence() + children.asSequence().flatMap { it.allChildren() }

fun Node.allParents(): Sequence<Node> = 
  listOfNotNull(parent).asSequence().flatMap { sequenceOf(it) + it.allParents() }

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to Create a Class That Can Have Parent and Child Relationship

Tag : chash , By : user119605
Date : March 29 2020, 07:55 AM
To fix the issue you can do Just for people in the future looking for this same solution, here is the full class:
public class Branch {
    public string Name { get; set; }
    public string Link { get; set; }
    public Branch Parent { get; set; }
    public TreeBranches Children { get; private set; }

    internal Branch(string Name, string Link) {
        this.Name = Name;
        this.Link = Link;
        this.Children = new TreeBranches(this);
    } // Branch - Constructor - Overload

    internal Branch(string Name, string Link, TreeBranches Children) {
        this.Name = Name;
        this.Link = Link;
        this.Children = Children;

        this.Children.ToList().ForEach(delegate(Branch branch) {
            branch.Parent = this;
    } // Branch - Constructor - Overload

    /// <summary>
    /// Returns a boolean indicating if the given Branch has any child Branches.
    /// </summary>
    public bool HasChildren {
        get { return this.Children.Count > 0; }
    } // HasChildren - Property - ReadOnly

    /// <summary>
    /// Gets the path from the oldest ancestor to the current Branch.
    /// </summary>
    public string Path {
        get {
            string Result = "";

            Branch parent = this;
            while (parent != null) {
                Result = string.Format("{0}/{1}", parent.Name, Result);
                parent = parent.Parent;
            } // while stepping up the tree

            return string.IsNullOrWhiteSpace(Result) ? "" : Result.Substring(0, Result.Length - 1);
        } // get
    } // Path - Property - ReadOnly

} // Branch - Class

public class TreeBranches : IList<Branch> {
    private List<Branch> branches = new List<Branch>();
    private Branch owner;

    public TreeBranches() {
        this.owner = null;

    public TreeBranches(Branch owner) {
        this.owner = owner;

    public void Add(Branch branch) {
        branch.Parent = this.owner;

    #region Standard IList Method Implementation

    IEnumerator<Branch> IEnumerable<Branch>.GetEnumerator() { return this.branches.GetEnumerator(); }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.branches.GetEnumerator(); }
    public int IndexOf(Branch item) { return this.branches.IndexOf(item); }
    public void Insert(int index, Branch item) { this.branches.Insert(index, item); }
    public void RemoveAt(int index) { this.branches.RemoveAt(index); }
    public Branch this[int index] {
        get { return this.branches[index]; }
        set { this.branches[index] = value; }

    public void Clear() { this.branches.Clear(); }
    public bool Contains(Branch item) { return this.branches.Contains(item); }
    public void CopyTo(Branch[] array, int arrayIndex) { this.branches.CopyTo(array, arrayIndex); }
    public int Count { get { return this.branches.Count(); } }
    public bool IsReadOnly { get { return this.IsReadOnly; } }
    public bool Remove(Branch item) { return this.branches.Remove(item); }

    #endregion Standard IList Method Implementation
} // TreeBranches - Class

JPA entities: How to establish relationship between Parent and multiple Child classes

Tag : java , By : Jesse
Date : March 29 2020, 07:55 AM
With these it helps If i got that right, class parent is an entity that keeps a one-to-one relationship with ChildType entity. Also ChildType is an abstract entity with 2 implementations, ChildA and ChildB.
So the JPA annotations configuration for each one of the entities, could be like that:
 Parent class as Entity
@Table(name = "PARENT")
public class Parent { // better name will do the job, because parent is often called
                      // the higher level class of the same hierarchy
  @Column(name = "PARENT_ID")
  private long id;

  @Column(name = "SOME_VALUE") //if you need to persist it
  private int someValue1;

  @OneToOne(optional = false, cascade = CascadeType.ALL)
  @JoinColumn(name = "FK_PARENT_ID")
  private ChildType child;

  // getters and setters
 ChildType class as Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ChildType { // this one is actually called parent class

  @GeneratedValue(strategy = GenerationType.TABLE)
  @Column(name = "CHILDTYPE_ID")
  protected Long id;

  @Column(name = "SOME_VALUE_2")
  private int someValue2; // or maybe protected. Depends if you need childs to access it

  @Column(name = "A_STRING")
  private String string; // or maybe protected. Depends if you need childs to access it

  // getters and setters
 ChildA as Entity
@Table(name = "CHILD_A")
public Class ChildA extends ChildType {

  @Column(name = "A_STRING")
  private String string;

  // getters and setters
 ChildB as Entity
@Table(name = "CHILD_B")
public Class ChildB extends ChildType {

  @Column(name = "AN_Integer")
  private Integer integer;

  // getters and setters

How do I create a relationship with Parent and Child using cypher?

Tag : csv , By : besn
Date : March 29 2020, 07:55 AM
To fix this issue It might be helpful if you provided your load csv
I am not sure what you provided in the way of labels on the nodes when you imported your data but this example should find children that have not already been matched to a parent category where the parent category exists in your data (i.e. greater than equal to 4). It should then match the parent based ont eh parent id on the node and create a :CHILD_OF relationship between the child and the parent.
match (child:Category)
where not (child-[:CHILD_OF]->())
and child.parent_id >= 4
with child
match (parent:Category)
where parent.category_id = child.parent_id
create child-[:CHILD_OF]->parent

Create a parent-child relationship after the parent type already exists

Tag : elasticsearch , By : John Phipps
Date : March 29 2020, 07:55 AM
it fixes the issue This is not allowed in ElasticSearch, so it mandates to create both parent and child in the same request or call.

JAVA Inheritance issues- this is about the relationship between parent and child classes

Tag : java , By : Tink
Date : March 29 2020, 07:55 AM
Any of those help So why is that I can cast a parent class as a child but not the other way around?
S = J; //aliasing ?
//J 0 S 1
System.out.println (S.x); // should print 0 but prints 1
J1 = (junior)S1; //Senior cannot be cast to junior, why?
System.out.println (S1.x); 
System.out.println (J1.x);// should print 1 but prints 0
Related Posts Related QUESTIONS :
  • Kotlin Class should have a single no-arg constructor
  • Kotlin Wildcard Capture on List Callback Parameter
  • How to pass functions to function in Kotlin
  • How can I serialize kotlin exposed sql dao
  • Difference between Any type and Generics in Kotlin
  • Kotlin : Interface with immutable property implemented by class with mutable
  • Idiomatic way to create n-ary cartesian product (combinations of several sets of parameters)
  • Serve favicon.ico and other static files with VertX
  • How to implement a getComponent(/*Class*/) method for video game in kotlin
  • For comprehensions with kotlin and arrow-kt library
  • how to access companion object from object instance in kotlin?
  • Protected members not accessible in extension functions?
  • ktor client https request with self-signed certificate
  • Kotlin contracts: link not-null of two properties
  • Kotlin coroutines: concurrent execution throttling
  • Kotlin: Update Immutable List Element
  • Kotlin with-statement as an expression
  • Kotlin class delegation features
  • Why does let not give me a non nullable integer in this case
  • Kotlin sequence concatenation
  • Kotlin - Create custom ext function for SpannableStringBuilder without duplicate arguments when declaring start, end &am
  • Kotlin actors goes to dead lock when capacity is less than number of messages
  • Can you concatenate statements at run-time in Kotlin?
  • Kotlin synchronized doesn't work properly
  • ojAlgo - Expressing Variables as Boundaries in Optimization?
  • Documenting Ktor routes with KDoc
  • Convert Set<Int> to varargs efficiently in Kotlin
  • Getting an error Using 'body(): ResponseBody?' is an error. moved to val with okhttp
  • Kotlin String to Int or zero (default value)
  • Return value only of the faster coroutine
  • Is there a Kotlin Coroutines Channel equivalent of RxJava's onDispose?
  • Create fat jar from kotlin multiplatform project
  • Short circuiting operation in Kotlin sequences
  • How to output deprecation warnings for Kotlin code?
  • Why does generated getter method have dollar signs in it?
  • For a final class why does when complain?
  • Reference value of constant with KDoc
  • How to create this coroutines in kotlin?
  • OkHttp: NoSuchMethodError copyInto in TlsUtil
  • Why do unreachable statements method not result in a compilation error?
  • Static/Const map key check at compile time
  • Escaping double quotes inside backticks
  • Does Kotlin have primitive types?
  • What is exactly null in kotlin and why i can't cause NPE with it?
  • Why would you use a Kotlin companion object rather than an initializer block for creation?
  • how to use operator overloading in Kotlin to divide a number by a numeric vector
  • How to use get() with backing fields in kotlin
  • How to map string to function and call it later
  • Kotlin enum constructor argument 'must be initialized' with companion object constant without qualifier name
  • Please explain to me class delegation in Kotlin
  • Error:(1, 41) Kotlin: Symbol is declared in module 'jdk.internal.opt' which does not export package 'jdk.i
  • How to properly make blocking service calls with Kotlin coroutines?
  • Gson SerializedName in a Kotlin interface
  • Kotlin convert FileTime to day, month, year
  • Kotlin how to move a file to a other directory?
  • If first param is true, then must pass second param in function
  • MutableLiveData for collections
  • How to replace long chain of forEach{} statements in Kotlin?
  • Shortened reference to class method when the receiver is known from context
  • how to break from lambda passed to recursive function when provided condition met
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com