Mohitt Mohitt - 2 months ago 26
Scala Question

Scala: Avoid var or mutable type

I have a pseudo-code like shown below. The

ItemChurner.churn()
is abstracted component which generates objects until
x
times, where
x
is unknown. :

def func: MyList = {

var list: MyList = MyList()

while(ItemChurner.canChurn) {
list = new MyList(ItemChurner.churn(), list)
}

list
}


Is there a way to avoid use of
var
?

Answer

If canChurn works as it should:

def func(churner: ItemChurner) = {
  val iterator = new Iterator {
    def hasNext = churner.canChurn; 
    def next = churner.churn()
  }
  iterator.toList
}

About version (of the question) that contained catched exception check for churn():

If really expect some exceptions, what's the point of canChurn then?

Anyway, if you care about exceptions:

 Iterator.continually(Try(churner.churn)).takeWhile(_.isSuccess).map(_.get).toList

This actually is not much precise, as churn might throw some other exception that has to be propagated, so here the scala's Exception helpers) come in hand:

def step = catching(classOf[NoMoreElementsException]) opt churner.churn()
Iterator.continually(step).takeWhile(_.nonEmpty).map(_.get).toList