admin管理员组

文章数量:1279084

I am working through Scala For The Impatient by Horstman. I'm doing this as a hobbyist. One of the questions is to write a unapplySeq function that extracts all of the components of a path.

package pathComponents

import java.nio.file.Path

class PathComponents(val myPath: Path)

object PathComponents:
  def apply(myPath: Path) = s"$myPath"

  def unapplySeq(input: Path): Seq[String] = 
    input.toString.stripPrefix("/").split("/").toSeq

I then wrote a test.

import java.nio.file.Path
import java.nio.file.Paths
import .scalatest.funsuite.AnyFunSuite
import pathComponents.PathComponents

import scala.language.postfixOps

class PathComponentsTest extends AnyFunSuite:
  val pathStr: String = "/home/cay/readme.txt"
  val myPath: Path = Paths.get(pathStr)

  test("Make PathComponents") {
    val comps: String = PathComponents(myPath)
    assert(comps == pathStr)
    println(comps)
  }

  test("Destructure PathComponents") {
    val PathComponents(comps*) = myPath
  }

The test will run, but I do get a warning:

pattern's type String* does not match the right hand side expressions's type String

I did figure out this works without a warning.

 test("Destructure PathComponents") {
    val PathComponents(root, myDir, myFile) = myPath
  }

What is causing the warning? Something tells me some sort of pattern matching might be happening behind the scenes, but I am not sure.

本文标签: Warning when writing unapplySeq in Scala to get path componentsStack Overflow