【问题标题】:Scala how to avoid using null?Scala如何避免使用null?
【发布时间】:2019-11-16 10:23:42
【问题描述】:

我是 Scala 新手,想知道在 Scala 中避免使用 null 的最佳方法是什么。如何重构以下逻辑:

 var nnode : Node = null
 if (i==str.length-1) {
     nnode = Node(ch,mutable.Map[Char,Node](), collection.mutable.Set(str))
 } else {
     nnode = Node(ch,mutable.Map[Char,Node](), collection.mutable.Set())
 }
 nnode...

【问题讨论】:

    标签: scala


    【解决方案1】:

    由于最后一个参数是唯一受影响的参数,因此其余代码只需要编写一次:

    val set = if (i == str.length - 1) collection.mutable.Set(str) else collection.mutable.Set()
    val nnode = Node(ch, mutable.Map[Char, Node](), set)
    

    您也可以避免val,并将set 的计算放在Node 构造函数中:

    val nnode = Node(
      ch,
      mutable.Map[Char, Node](),
      if (i == str.length - 1) collection.mutable.Set(str) else collection.mutable.Set()
    )
    

    【讨论】:

      【解决方案2】:
      var nnode: Node = 
        if (i == str.length - 1) Node(ch, new mutable.Map[Char, Node](), mutable.Set(str))
        else Node(ch, new mutable.Map[Char, Node](), mutable.Set.empty)
      

      【讨论】:

      • 你也可以使用val
      猜你喜欢
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多