• Scala 中 for 循环 和 generator 的使用例子


    这个例子是,从每个list中,找到age最大的那个node。

    class Node(vName: String, vAge: Int) {
      // Entity class
      var name: String = vName
      var age: Int = vAge
    }
    
    object TestGenerator {
    
      def main(args: Array[String]): Unit = {
        test()
      }
    
      def test(): Unit = {
        // This test case is to find out the max age node from each node's list
    
        // First, define the node 1,2,3
        val node1 = new Node("name-1", 1)
        val node2 = new Node("name-2", 2)
        val node3 = new Node("name-3", 3)
    
        // Second, def some List containing nodes
        val list1: List[Node] = List(node1, node2, node3)
        val list2: List[Node] = List(node1)
        val list3: List[Node] = List(node1, node2)
        val list4: List[Node] = List()
        val list5: List[Node] = Nil
        val list6: List[Node] = null
    
    
        // ==== Test Case 1 ====
        // In this test, the generator excluded the Nil and List() and null, and take the "node" out of headOption" which is Option[Node]
        // The returns are collected into node as Node
    
        val allList: Seq[List[Node]] = Seq(list1, list2, list3, list4, list5, list6)
    
        val result1 = for {
          list: List[Node] <- allList // The type List[Node] is necessary for this situation, it can help to filter out list6 (null)
          node <- list.sortWith(_.age > _.age).headOption
        } yield node
    
        for (r <- result1) {
          println(r.name)
        }
    
        println("======================================================")
    
        // *****************************************************************************
    
        // ==== Test Case 2 ====
        // In this test, use get() function to get back the list instead of Seq[List[Node]]
    
        def get(i: Int): List[Node] = {
          i match {
            case 1 => list1;
            case 2 => list2;
            case 3 => list3;
            case 4 => list4;
            case 5 => list5;
            case 6 => list6;
          }
        }
    
        // Define the array to contain the test lists
        // List 1-5 will be used for this test, but list6 (null) cannot be handled in this approach
        val arr = List(1, 2, 3, 4, 5) // list6 (null) cannot be handled thus only 1-5 here
    
        val result2 = for {
          i <- arr
          node <- get(i).sortWith(_.age > _.age).headOption
        } yield node
    
        for (r <- result2) {
          println(r.name)
        }
    
      }
    }
  • 相关阅读:
    模板方法模式
    策略模式
    享元模式
    组合模式
    桥接模式
    外观模式
    代理模式
    装饰者模式
    适配器模式
    类之间的关联关系和依赖关系
  • 原文地址:https://www.cnblogs.com/pekkle/p/9149957.html
Copyright © 2020-2023  润新知