`++` - The operator on two arrays returns ArraySeq when using parameters of type

I tried to implement a simple binary tree, and that is what I came up with:

object main {

  class Node[A]

  case class EmptyNode[A](value: A) extends Node [A]

  case class NonEmptyNode[A](left: Node[A], right: Node[A]) extends Node[A]

  def traverse[A](tree: Node[A]): Array[A] = tree match {
    case NonEmptyNode(l: Node[A], r: Node[A]) => traverse(l) ++ traverse(r)
    case EmptyNode(v: A) => Array(v)
  }

  def main(args: Array[String]): Unit = {
    val binaryTree =
      NonEmptyNode(
        NonEmptyNode(
          EmptyNode("He"),
          EmptyNode("llo ")
        ),
        NonEmptyNode(
          EmptyNode("Wor"),
          EmptyNode("ld")
        )
      )

    val output = traverse(binaryTree).reduce((a, b) => a + b)

    println(output)
  }
}

Now I am wondering why this is not working by telling me:

Error:(11, 62) type mismatch;
 found   : scala.collection.mutable.ArraySeq[A]
 required: Array[A]
    case NonEmptyNode(l: Node[A], r: Node[A]) => traverse(l) ++ traverse(r)

when I fix Ahow String, for example, it works:

object main {

  class Node

  case class EmptyNode(value: String) extends Node

  case class NonEmptyNode(left: Node, right: Node) extends Node

  def traverse(tree: Node): Array[String] = tree match {
    case NonEmptyNode(l: Node, r: Node) => traverse(l) ++ traverse(r)
    case EmptyNode(v: String) => Array(v)
  }

  def main(args: Array[String]): Unit = {
    val binaryTree =
      NonEmptyNode(
        NonEmptyNode(
          EmptyNode("He"),
          EmptyNode("llo ")
        ),
        NonEmptyNode(
          EmptyNode("Wor"),
          EmptyNode("ld")
        )
      )

    val output = traverse(binaryTree).reduce((a, b) => a + b)

    println(output)
  }
}

which will print Hello World.

+4
source share
1 answer

Since nothing is known about the type A, it is impossible to create Array[A]. Since he cannot build Array[A]from two Array[A]s, he returns instead ArraySeq.

If you really want to create arrays, you must provide ClassTagfor A:

object main {

  class Node[A]

  case class EmptyNode[A](value: A) extends Node [A]

  case class NonEmptyNode[A](left: Node[A], right: Node[A]) extends Node[A]

  import scala.reflect.ClassTag
  def traverse[A: ClassTag](tree: Node[A]): Array[A] = tree match {
    case NonEmptyNode(l, r) => traverse(l) ++ traverse(r)
    case EmptyNode(v) => Array(v)
  }

  def main(args: Array[String]): Unit = {
    val binaryTree =
      NonEmptyNode(
        NonEmptyNode(
          EmptyNode("He"),
          EmptyNode("llo ")
        ),
        NonEmptyNode(
          EmptyNode("Wor"),
          EmptyNode("ld")
        )
      )

    val output = traverse(binaryTree).reduce((a, b) => a + b)

    println(output)
  }
}

Print

Hello World

, Array[A] A, , Array[A] A: , , , Object s. ClassTag , , .

+4

Source: https://habr.com/ru/post/1694689/


All Articles