0

I am new to scala and I came across this code:

  def map_2[A, B](l: List[A])(f: A => B): List[B] = {
    val buf = new collection.mutable.ListBuffer[B]

    @tailrec
    def go(l: List[A]): Unit = l match {
      case Nil => ()
      case Cons(h, t) => buf += f(h); go(t)
    }

    go(l)
    List(buf.toList *)
  } // converting from the standard Scala list to the list we've defined here

I understand what it does (it maps a list), but I am getting a compilation error at List(buf.toList *) saying that Cannot resolve symbol *.

I tried the suggested fixes by intellij idea like import scala.language.postfixOps (even though I don't know whats this), but no luck.

What is this error and how to solve it?

  • I would go back to the place where you found this code, since it is indeed invalid Scala. Perhaps the `*` is just part of the description? – Tim Feb 18 '22 at 16:16
  • @Tim this is from functional programming in scala book, they put a comment at the last line to explain what `List(buf.toList *)` is doing and it seemed to me that the * is an operator that is similar to the ... spread operator in dart that spread a list into its elements. Is this not a valid scala syntax? and if not then how to spread the elements inside the buffered list in order to transfer them into a normal `List`? –  Feb 18 '22 at 16:20
  • 1
    @User0123 AFAIK the right syntax for that is `List(buf.toList : _*)` although you are creating a `List` to then creating a `Seq` to then pass it to a varargs of the `List` method to create a `List`... seems completely unnecessary and stupid, just do `buf.toList` – Luis Miguel Mejía Suárez Feb 18 '22 at 16:29
  • @LuisMiguelMejíaSuárez yeah you are right I just discovered that this is the right syntax, please post it as an answer. And just fyi, this is not my code this is a code from a book for teaching purposes but it seems to be outdated (from 2014) –  Feb 18 '22 at 16:31

0 Answers0