Scala syntax problems for expressing understanding

Is it possible to make an if statement in a 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 processTemplateDTO.getProcessTemplateif processTemplate.get.trainingsprocess.isDefinedtrue

Is it possible?

thank

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)
    }
+4
source share
2 answers

Yes, you can use a block ifin a block for, 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 the 2nd case, you also need to give another block, because without it it will return Any

Hope this helps!

+1
source

Yes it is possible. You can see the code below 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
+2
source

Source: https://habr.com/ru/post/1690548/


All Articles