1

我是 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...
4

2 回答 2

4

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

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

您还可以避免 aval并将计算set放在Node构造函数中:

val nnode = Node(
  ch,
  mutable.Map[Char, Node](),
  if (i == str.length - 1) collection.mutable.Set(str) else collection.mutable.Set()
)
于 2019-11-16T11:19:17.357 回答
1
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)
于 2019-11-16T10:34:44.807 回答