Felix
Felix

Reputation: 5619

Scala syntax problems in for comprehension statement

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

enter image description here

  trainedProcessTemplate <- Nil
    _ = if (processTemplate.get.trainingsprocess.get != null) {
      processTemplateDTO.getProcessTemplate(processTemplate.get.trainingsprocess.get, clientId)
    }

Upvotes: 4

Views: 150

Answers (2)

Arpit Suthar
Arpit Suthar

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

S.K
S.K

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

Related Questions