简体   繁体   English

Scala案例类

[英]Scala case Class

在此处输入图片说明

Below is the code snippet:下面是代码片段:

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}")
 }
}
}

When I am calling File and Folder method (defined as case class) in main I am getting error, I am not sure what I am doing wrong.当我在 main 中调用文件和文件夹方法(定义为案例类)时,我收到错误,我不确定我做错了什么。

So your sequence is incorrect.所以你的顺序是不正确的。

You should put a comma after every element in your sequence.您应该在序列中的每个元素后放置一个逗号。

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

And the result:结果:

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

So everything is okay :) Except that commas所以一切都很好:) 除了逗号

In your code, my proposal is to add type to resources and use only Seq to create a sequence.在您的代码中,我的建议是为资源添加类型并仅使用Seq创建序列。 The code will be more readable.代码将更具可读性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM