Scala how to avoid using null?

Ashika Umanga Umagiliya

I am new to Scala and want to know whats the best way to avoid using null in Scala.How to refactor following logic :

 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...
Tim

Since the last parameter is the only one that is affected, they rest of the code only needs to be written once:

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

You could also avoid a val and put the calculation of set inside the Node constructor:

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related