trying to avoid mutables in scala.. is this the right way?

I'm trying to avoid mutable variables as much as possible, but sometimes it just feels too hard, and I don't want to end with an extremely complicated code

Nevertheless I found this way to do it, but it certainly feels like cheating

I'm parsing a query, and I find find a field!value, I want to translate it to field:<>value, and then go on processing, so I came out with this code to avoid mutables, or at least to have them confined...

val (operator, negated) = {
  var operator = ConditionOperator.toConditionOperator(parsedOperator)
  var negated = parsedNegated == "!"
  // field!value => field notEqual value
  if (negated && operator == ConditionOperator.Unknown) {
    negated = false
    operator = ConditionOperator.NotEqual
  }
  (operator, negated)
}

Is this the right way to do it??? or is there a more idiomatic (and clear!) way to achieve this kind of things?

Answers


This is indeed cheating since var is mutable!

The way to correct this is to simply return the if-statement's result directly:

val (operator, negated) = {
  val operator = ConditionOperator.toConditionOperator(parsedOperator)
  val negated = parsedNegated == "!"
  // field!value => field notEqual value
  if (negated && operator == ConditionOperator.Unknown)
    (ConditionOperator.NotEqual, false)
  else
    (operator, negated)
}

Need Your Help

How do I import a list ? (python)

python list file import choice

I am new to Python..(I am studying it for a week or so)

Android mediaplayer not working

android

I have created an activity which receives messages realtime. Sometimes the message is just a notification, other times the message leads to a yes/no alert dialog pop up.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.