You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala案例类实例化报错:main方法创建File/Folder对象时出错

Fixing Your Scala Case Class & Seq Compilation Errors

Let's walk through the issues in your code step by step to get it running properly:

1. Missing Commas Between Sequence Elements

This is the biggest issue causing compilation failures. In Scala, when you define a Seq (or any collection) with multiple elements, you must separate each element with a comma. Your code has no commas between the File and Folder instances in the resources Seq—Scala interprets this as trying to call the first File instance as a function with the Folder as an argument, which makes no sense here.

Fix:

Add commas after every element in the Seq:

val resources = Seq[Resources] (
  File("ex1.Scala", Some(Folder("example", Some("~/Dev")))),
  Folder("temp"),
  Folder("bin", Some("/usr")),
  File(".Clouder")
)

2. Typos That Will Cause Runtime or Readability Issues

  • The main method parameter is misspelled as agrs—it should be args (this is a standard convention, and while it won't break compilation, it's confusing and bad practice).
  • In your pattern match, you wrote FOlder (with a capital O) instead of Folder—this will cause a MatchError at runtime because it won't match any Folder instances. Correct the spelling to Folder.

Adding spaces around commas and parentheses makes your code easier to read, like Some(Folder("example", Some("~/Dev"))) instead of cramming everything together.

Full Corrected Code

package caseClassExp

sealed trait Resources {
  def fullpath: String
}

case class Folder(name: String, path: Option[String] = None) extends Resources {
  def fullpath: String = path match {
    case Some(p) => List(p, name).mkString("/")
    case None => s"./$name"
  }
}

case class File(name: String, folder: Option[Folder] = None) extends Resources {
  def fullpath: String = folder match {
    case Some(f) => List(f.fullpath, name).mkString("/")
    case None => s"./$name"
  }
}

object caseClass {
  def main(args: Array[String]): Unit = {
    val resources = Seq[Resources] (
      File("ex1.Scala", Some(Folder("example", Some("~/Dev")))),
      Folder("temp"),
      Folder("bin", Some("/usr")),
      File(".Clouder")
    )
    
    resources foreach {
      case f: File => println(s"File: ${f.fullpath}")
      case f: Folder => println(s"Folder: ${f.fullpath}")
    }
  }
}

What the Fixed Code Does

When you run this, it will output the full paths of each resource correctly:

File: ~/Dev/example/ex1.Scala
Folder: ./temp
Folder: /usr/bin
File: ./.Clouder

内容的提问来源于stack exchange,提问作者Harshit Kakkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:11:33