Scala案例类实例化报错:main方法创建File/Folder对象时出错
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 beargs(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 ofFolder—this will cause aMatchErrorat runtime because it won't match anyFolderinstances. Correct the spelling toFolder.
3. Optional (But Recommended) Formatting Tweaks
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

