0

I found an example of code building a LinkedList from scratch in Scala and I could not understand the last line in the example. Here is the example :

scala> class MyList (val head : Any, val tail : MyList) {
     | def isEmpty = (head == null && tail == null)
     | def length : Int = if (isEmpty) 0 else 1 + tail.length
     | override def toString: String = if (isEmpty) "" else head + " " + tail
     | }
defined class MyList

scala> var list = new MyList (null, null)
list: MyList =

scala> list.length
res3: Int = 0

scala> list.isEmpty
res4: Boolean = true

scala> list = new MyList ("ABC", list)
list: MyList = ABC

scala> list.length
res5: Int = 1

scala> list.isEmpty
res6: Boolean = false

scala> list = new MyList("XYZ", list)
list: MyList = XYZ ABC

scala> list = new MyList ("123", list)
list: MyList = 123 XYZ ABC

scala> list.tail.head
res7: Any = XYZ

I dont understand why list.tail.head prints "XYZ". In fact I cannot reason out what list.tail.head should print a priori given the definition of the class MyList as given. Any help in understanding what is going on would be appreciated.

1 Answer 1

1

Remember that constructor parameters defined with val are public member and thus accessible (have a look here). Quoting from the link:

If the field is a val, Scala generates only a [public] getter method for it.

head contains the one element that we consider the first, tail another list of elements that we consider the tail. It's a recursive structure where an instance of an object contains a reference to another instance of the same object.

In your example, after you built a list after the other, it's like you have (this is not actual code):

MyList(
  head = "123"
  tail = MyList(
    head = "XYZ"
    tail = MyList(
      head = "ABC"
      tail = MyList(
        head = null
        tail = null
      )
    )
  )
)

list.tail = MyList(
  head = "XYZ"
  tail = MyList(
    head = "ABC"
    tail = MyList(
      head = null
      tail = null
    )
  )
)

list.tail.head = "XYZ"
Sign up to request clarification or add additional context in comments.

2 Comments

Ah! I didnt know that constructor params auto define public members. And the writing out of the MyList data structure at the end helped clarify the picture immensely. thanks!! shouldnt the last tail be a tail = MyList (head = null tail = null). if yes, then if you make that edit I can accept your answer.
They define getters and/or setters if you use val or var in the definition, otherwise not. Yes, it should, I'll correct it

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.