Reputation: 5619
Is it possible to make an if statement in a for block?
I have the following:
val process = for {
stepIds <- processTemplateDTO.getProcessStepTemplateIds(processTemplateId)
allApprovedProcessTemplates <- processTemplateDTO.getApprovedProcessTemplates(clientId) //Get all approved process templates
processTemplate <- processTemplateDTO.getProcessTemplate(processTemplateId, clientId) // Get the Process Template
prerequisites <- getProcessTemplateForEdit(processPrerequisitesDTO.getProcessPrerequisiteProcessTemplateIdsByProcessTemplateId(processTemplateId), clientId)
postConditions <- getProcessTemplateForEdit(processPostConditionsDTO.getProcessPostConditionProcessTemplateIdsByProcessTemplateId(processTemplateId), clientId)
approvedProcessTemplate <- processTemplateDTO.getProcessTemplate(processTemplate.get.approveprocess, clientId)
if (processTemplate.get.trainingsprocess.isDefined) {
trainedProcessTemplate <- processTemplateDTO.getProcessTemplate(processTemplate.get.trainingsprocess.get, clientId)
}
And I only want to call the processTemplateDTO.getProcessTemplate
if processTemplate.get.trainingsprocess.isDefined
is true
is this possible?
Thanks
also tried this way:
trainedProcessTemplate <- {
if (processTemplate.get.trainingsprocess.isDefined) {
processTemplateDTO.getProcessTemplate(processTemplate.get.trainingsprocess.get, clientId)
} else {
None
}
}
UPDATE
trainedProcessTemplate <- Nil
_ = if (processTemplate.get.trainingsprocess.get != null) {
processTemplateDTO.getProcessTemplate(processTemplate.get.trainingsprocess.get, clientId)
}
Upvotes: 4
Views: 150
Reputation: 754
Yes it is possible to use if
block in for
block, there are two ways
for {
a <- somework1 // returns boolean
b <- somework2 if(a)
} yield (a, b) //anything you like
or you can try
for {
a <- somework1 // returns boolean
b <- if(a) somework2 else somework3
} yield (a, b) //anything you like
In 2nd way you have to give else block as well because without that it will return Any
Hope this helps!
Upvotes: 1
Reputation: 530
Yes, It is possible. You can see the below code for reference -
val list = List(1,2,3,4)
val result = for {
id <- list
_ = if (id < 2) {
println(s"Hello I am $id")
}
} yield id
Upvotes: 2