Scala:使用对象,案例类和listMap进行建模

时间:2018-04-04 08:08:07

标签: scala functional-programming

我想为函数定义我的返回类型,例如:

def getMovieInformation (name: String): Information = ???

然后当然我需要这样的东西:

case class Information (name: String, inTheathers: Boolean)

到目前为止,这么好。但现在我想从内部API获取信息, 这给了我一个提前的结果,普通用户无法理解,所以我想使用mapList StringString来返回更一般的信息,例如:

val qualityFeedback =  ListMap(
  "advance info" -> "Movie has a great quality",
  "another advance info " -> "Movie has a bad quality"
)

然后我的案例类将是:

case class Information (name: String, inTheathers: Boolean, qualityFeedback: String)

好的,如果我想把所有东西放在一起,我会:

object Movie {
  case class Information (name: String, inTheathers: Boolean, qualityFeedback: String)

  val qualityFeedback =  ListMap("advance info" -> "Movie has a great quality","another advance info " -> "Movie has a bad quality")
}

在另一个课程中,我将导入Movie对象,并将具有:

def getMovieInformation (movieName: String) : Information = {
   //Call internal API and get the advance value match it with the list map above and get an explanatory string. 
   val feedback = ???  

   val isInTheather: Boolean = ???  

   //Need to return Movie.Information
   val information: Movie.Information = (name = movieName, inTheater = isInTheater, qualityFeedback = feedback)  

   Ok(views.html.movie(information)) 
}

我不喜欢'像上面的代码;即使在语义上它是正确的。仅仅因为我有Movie.Information。我也不想提出case类,因为我想在对象中用qualityFeedback打包它。

有更好/更清洁的方式对此进行建模吗?或者更确切地说,我如何以功能方式对其进行建模(不使用对象和案例类)。

1 个答案:

答案 0 :(得分:0)

如果您不喜欢代码中的Movie.Information,则只需import Movie._

import Movie._
def getMovieInformation (name: String) : Information = {
   //Call internal API and get the value based on the key from   Movie.qualityFeedback
   //Now just return Information
}

Scala中对象内部定义的类与Java中类中的静态类几乎相同。除非您导入(或在java中进行静态导入),否则您将使用两种语言中的额外Movie.