当前位置:网站首页>Scala for derivation: the ability to define a value in the first part of a for expression and use it in subsequent (outer) expressions

Scala for derivation: the ability to define a value in the first part of a for expression and use it in subsequent (outer) expressions

2022-06-22 16:47:00 ZH519080

stay scala Of for In circulation , How to... When containers are not applicable , stay for loop ( outside ) Call it later for Properties defined in . Object containing None Attribute in for How to eliminate ???

Both cases are written in the same function :

  /**for deduction : In the for The first part of the expression defines the value , Use this value in the following expression 
    *  Such as upcaseBreed stay println Use in */
  def roundingFor: Unit ={

    val dogBreeds = List("Doberman","Dachshund","Scottish","Portuguese")
    for {
      breed <- dogBreeds
      /** Even though upcaseBreed The value of is immutable ,upcaseBreed There is no need to set it in the front , But you don't need to use val Keywords are qualified */
      upcaseBreed = breed.toUpperCase
    } println(upcaseBreed)  // Equivalent to the for Use after the loop for Internal properties 

    println(
      """    *
        |   ***
        |  *****
        |*********
        |  *****
        |   ***
        |    *
      """.stripMargin)


    val catBreeds = List(Some("Dane"),None,Some("Yorkshire"),None,Some("Scottish"))
    println("first pass:")
    for {
      /** Each extracted element is Option object . The following code will use the arrow character to extract Option The value in , The derivation is effectively checked and ignores None, There will be no exceptions */
      breedOption <- catBreeds
      breed <- breedOption
      upcaseBreed = breed.toUpperCase
    } println(upcaseBreed)

    println("second pass:")
	/** At the first for Defined inside the loop breed and upcaseBreed The attribute is in the second... Below for Use in loop */
    for {
      /** this for The derivation uses pattern matching , Only when breedOption yes Some Type , expression Some(breed) <- catBreeds Will be executed and extracted breed*/
      Some(breed) <- catBreeds
      upcaseBreed = breed.toUpperCase
    } println(upcaseBreed)
  }

 

原网站

版权声明
本文为[ZH519080]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221523254782.html