Reputation: 4878
I am missing something over here.
I have a case class that contains some string members and 2 enums.
class constructor receive the enum values as string.
I use the command:
var order = Order.withName(orderInput) //Order is an object that extends Enumeration
In order to avoid exception on class construction (if the input string is not in the enum values, I set the enum value upon construction of the class to a default value.
I have a validation function for this case class, during validation i set the enum, this case if i get exception, its during validation and not while constructing the object.
The code looks like:
Enum code:
object Order extends Enumeration {
type OrderType = Value
val asc = Value("asc")
val desc = Value("desc")
def validateOrder(orderInput:String)
{
val orderValidate = Order.isOrderType(orderInput)
if (!orderValidate)
throw new Exception("Order is invalid ("+orderInput+")!")
}
def isOrderType(s: String) = values.find(_.toString.equals(s)).isDefined
}
My Case Class:
case class ProductsByCategoriesRequest(langaugeInput:String, tenantIdInput:String, categoriesIds:List[String], startInput:Integer, maxResultsInput:Integer,sortInput:String,orderInput: String)
extends ProductSorting
with Paging
with LanguageFilter
with TenantFilter
with BaseRequest
{
var order = Order.asc //default value
var sortField = Field.name //default value
val maxResults = maxResultsInput
val start = startInput
val language = langaugeInput
val tenantId = tenantIdInput
def validate()
{
if (StringUtils.isListNullOrEmpty(categoriesIds))
throw new Exception("Categories Ids list is invalid")
validateLanguage
validateTenant
Order.validateOrder(orderInput)
var order = Order.withName(orderInput)
Field.validateField(sortInput)
var sortField = Field.withName(sortInput)
}
}
What is weird ? During validation the enum is changed, but later on when i use this object, and getting the value of the enum, it will always be "asc" as the default. although i set it as "desc" and saw it changes!
This probably has something to do with objects behavior in scala and the fact that var does not keep the true status of the member after existing the scope maybe ?
Thanks
Upvotes: 2
Views: 286
Reputation: 3298
You are defining new variables (with narrower scope) named order and sortField in validate
instead of assigning the values to the previously declared vars - remove the var
from the order
and sortField
assignments there.
So:
var order = Order.withName(orderInput)
Field.validateField(sortInput)
var sortField = Field.withName(sortInput)
Should become:
order = Order.withName(orderInput)
Field.validateField(sortInput)
sortField = Field.withName(sortInput)
Upvotes: 2