Home > front end >  Add ArrayBuffer Element via def in Scala
Add ArrayBuffer Element via def in Scala

Time:08-28

I am curious as to how to add an ArrayBuffer element via a def. E.g.

def addToArray[T](data: ArrayBuffer[T]): ArrayBuffer[T] = {
      return(data  = T("XYZ"))
}

I tried this but no go. I assume we cannot do this generically, but I would like to know how to do this. If I do this, return(new ArrayBuffer[T]()), it works. Not the most difficult but somehow escaping me.

CodePudding user response:

Just give the def your generic buffer and the element you want to add then return it:

  def addToArrayBuffer[T](data: ArrayBuffer[T], elem: T): ArrayBuffer[T] = {
    data  = elem
    data
  }
  println(addToArrayBuffer(ArrayBuffer(1, 2, 30), 4)) // ArrayBuffer(1, 2, 30, 4)

If you are not passing the element you want to add as a parameter to the def, then you can't add it inside the def. The idea is that you cannot create an instance of a type parameter, because instantiation requires a constructor which is unavailable if the type is unknown. This restriction is mentioned in the Java generics spec here:

Cannot Create Instances of Type Parameters: You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:

public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}

Wikipedia also explains this very nicely:

Java generics differ from C templates. Java generics generate only one compiled version of a generic class or function regardless of the number of parameterizing types used. Furthermore, the Java run-time environment does not need to know which parameterized type is used because the type information is validated at compile-time and is not included in the compiled code. Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown.

Note that there might be a workaround to this using reflection, which is further detailed in the spec.

  • Related