📜  斯卡拉 |任何一个

📅  最后修改于: 2022-05-13 01:55:15.020000             🧑  作者: Mango

斯卡拉 |任何一个

在 Scala Either中,功能与Option完全相同。唯一不同的是,使用 Either 返回一个字符串是可行的,该字符串可以解释有关出现的错误的说明。 Either有两个孩子,分别命名为RightLeft ,其中Right类似于Some类, LeftNone类相同。 Left用于失败,我们可以返回在Either的子Left内部发生的错误,Right用于Success。
例子:

Either[String, Int]

在这里, String用于 Either 的Left子节点,作为 Either 的 left 参数, Int用于Right子节点,作为 Either 的 right 参数。现在,让我们借助一些示例详细讨论它。

  • 例子 :
    // Scala program of Either
      
    // Creating object and inheriting
    // main method of the trait App
    object GfG extends App
    {
      
        // Defining a method and applying 
        // Either
        def Name(name: String): Either[String, String] =
        {
          
            if (name.isEmpty) 
                // Left child for failure
                Left("There is no name.")
      
            else
                // Right child for success
                Right(name)
        }
          
        // Displays this if name is 
        // not empty
        println(Name("GeeksforGeeks"))
      
        // Displays the String present
        // in the Left child 
        println(Name(""))
    }
    
    输出:
    Right(GeeksforGeeks)
    Left(There is no name.)
    

    在这里, isEmpty方法检查 name 的字段是空的还是填充的,如果它是空的,那么 Left child 将返回它自己内部的 String,如果这个字段不为空,那么 Right child 将返回指定的名称。

  • 例子 :
    // Scala program of Either with
    // Pattern matching
      
    // Creating object and inheriting
    // main method of the trait App
    object either extends App
    {
      
        // Defining a method and applying 
        // Either
        def Division(q: Int, r: Int): Either[String, Int] =
        {
            if (q == 0) 
                // Left child for failure 
                Left("Division not possible.")
            else
                // Right child for success
                Right(q / r)
        }
      
        // Assigning values 
        val x = Division(4, 2)
      
        // Applying pattern matching
        x match
        {
            case Left(l) => 
          
            // Displays this if the division
            // is not possible
            println("Left: " + l)
          
            case Right(r) => 
          
            // Displays this if division 
            // is possible
            println("Right: " + r)
        }
    }
    
    输出:
    Right: 2
    

    在这里,除法是可能的,这意味着成功,所以Right返回 2。在这里,我们在 Either 的这个例子中使用了模式匹配。