Search code examples
scalastacktoarray

In Scala, how to use 'toArray()' to turn a stack to a array?


I use the 'toArray' api of immutable.Stack like the codes below in Scala, but it reports error.

var stack1 = mutable.Stack[Long]()
val array = stack1.toArray();

It reports 'Cannot resolve reference toArray with such signature' about toArray and "unspecified value parameters" about the '()' of toArray() !

An image


Solution

  • TLDR

    the correct way is to call toArray without parentheses

    Explanation

    toArray function has the following signature (you can use tab to expand signatures in Scala repl):

    scala> stack1.toArray
       def toArray[B >: Long](implicit evidence$1: scala.reflect.ClassTag[B]): Array[B]
    

    It expects ClassTag implicit parameter:

    scala> stack1.toArray
    res2: Array[Long] = Array()
    
    scala> stack1.toArray(scala.reflect.classTag[Long])
    res3: Array[Long] = Array()
    

    In the first case, parameter is substituted by compiler. In the second case parameter passed explicitly.