scalacollectionslistbuffer

Issues using ListBuffer in Scala


package com.listbuffer.ex

import scala.collection.mutable.ListBuffer

object IUEReclass{
   def main(args: Array[String]) {

     val codes = "XY|AB"
     val codeList = codes.split("|")
     var lb = new ListBuffer[String]()

     codeList.foreach(lb += "XYZ")

       val list = lb.toList

   }

I'm getting following exception.

[ERROR] C:\ram\scala_projects\Fidapp\src\main\scala\com\listbuffer\ex\ListBufferEx.
scala:38: error: type mismatch;
[INFO]  found   : scala.collection.mutable.ListBuffer[String]
[INFO]  required: String => ?
[INFO]
                lb += "XYZ"
[INFO]`enter code here`
                          ^
[ERROR] one error found

Solution

  • The type of codeList is Array[String], which is because split method on Strings will return an Array[String].

    Now you have a Array[String] on which you are calling the foreach method, so what you should pass to this function is a function from a String to Unit. What you are giving it instead is a ListBuffer[String], because += method on a ListBuffer will return a ListBuffer. This type inconsistency will cause the compile error.

    Details on foreach method

    From the Scala docs of foreach method:

    Applies a function f to all elements of this array.

    In this case elements of this array are of type String so the provided function to foreach should accept inputs of type String.

    Alternatives

    If adding all elements of codeList to the ListBuffer is your intention, as mentioned by Paul in comments, you can do it with

    codeList.foreach(code => lb += code)
    

    or

    codeList.foreach(lb += _)
    

    Alternatively you can use the appendAll method from ListBuffer:

    lb.appendAll(codeList)
    

    which

    Appends the elements contained in a traversable object to this buffer.

    according to the Scala Docs.