需要帮助在函数式编程风格中重构这个scala方法

nul*_*ull 2 functional-programming scala

我有这个scala方法,从一些参数构建一个Map:

def foo(name: Option[String], age: Option[Int], hasChilds: Option[Boolean], 
    childs: Option[List[Map[String, Any]]]): Map[String,Any] = {

    var m = Map[String, Any]()

    if (!name.isEmpty) m += ("name" -> name.get)
    if (!age.isEmpty) m += ("age" -> age.get)
    if (!hasChilds.isEmpty) m += ("hasChilds" -> hasChilds.get)
    if (!childs.isEmpty) m += ("childs" -> childs.get)

    m
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法以更多功能的方式重构代码?

var在这种情况下是否有可能使用?

elm*_*elm 6

一种方法包括扁平化不可变的Map,像这样,

def foo(name: Option[String], 
        age: Option[Int], 
        hasChilds: Option[Boolean], 
        childs: Option[List[Map[String, Any]]]): Map[String,Any] = {

  Map( ("name" -> name), 
       ("age" -> age),
       ("hasChilds" -> hasChilds),  
       ("childs" -> childs)).collect { case(a,Some(b)) => (a,b) }
}
Run Code Online (Sandbox Code Playgroud)