Home > other >  Scala - Object & Class
Scala - Object & Class

Time:09-30

I am beginner in scala. Got a doubt while trying to implement Collections..

class MyLinkedHashMap[K, V] {

  var initialCapacity = 16
  private var index = 0
  var map: Array[Node[K, V]]
  var head: Node[K, V]
  var tail: Node[K, V]

  class Node[K, V] {
    var key: K;
    var value: V;
    var next: Node[K, V]
    var before: Node[K, V]
    var after: Node[K, V]

    def Node(key: K, value: V, next: Node[K, V]) {
      this.key = key
      this.value = value
      this.next = next
    }
  }

  def MyLinkedHashMap() {
    map = new Array[Node[K, V]](initialCapacity)
  }

  def MyLinkedHashMap(initialCapacity: Int) {
    if (initialCapacity < 0) {
      throw new IllegalArgumentException();
    }
    map = Array[Node[K, V]](initialCapacity)
  }
  private def hash(key:K): Int = {
    return Math.abs(key.hashCode()) % initialCapacity
  }

  def put(key: K, value: V): Unit = {
    if (key == null) {
      return;
    }
    var hashIndex = hash(key)
    val newNode = new Node[K, V](key, value, null)
  }
}

The error I get at Line no: 42 is

Too many arguments for constructor Node

However if I declare class Node in the object of MyLinkedHashMap I do not get this error. I wanted to know the reason for this error.

And I didn't want the Node class to be abstract, however the following error is raised when not declared abstract.

Class 'Node' must either be declared abstract or implement abstract member 'next: Node[K, V]' in 'MyLinkedHashMap.Node'

Why is it neccessary for Node class to be abstract?

CodePudding user response:

The error I get at Line no: 42 is

Too many arguments for constructor Node

Here, you are calling Node's constructor with three arguments:

new Node[K, V](key, value, null)

But here you define the Node class's primary constructor with no parameter list:

class Node[K, V]

And there is no auxiliary constructor defined either.

So, the only constructor that exists on Node is the one that takes no parameters but you are calling it with three arguments.

If you want to call a constructor with three arguments, you need to define a constructor (probably the primary constructor) which takes three parameters, maybe something like this:

class Node[K, V](var key: K, var value: V, var next: Node[K, V])
  • Related