代码之家  ›  专栏  ›  技术社区  ›  Harshit Kakkar

scala case类

  •  -1
  • Harshit Kakkar  · 技术社区  · 7 年前

    enter image description here 下面是代码段:

    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(agrs: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}")
     }
    }
    }
    

    当我在main中调用文件和文件夹方法(定义为case类)时,我会出错,我不确定我做错了什么,请问有人能帮忙吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Patryk Rudnicki    7 年前

    所以你的顺序是错误的。

    您应该在序列中的每个元素后面加一个逗号。

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

    结果是:

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

    所以一切都很好:)除了逗号

    在您的代码中,我的建议是向资源添加类型并仅使用 Seq 创建序列。代码将更加可读。

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