scala语言示例
Scala | 任一关键字 (Scala | Either Keyword)
Either is a container similar to the option which has two values, they are referred to as children. The left and right children are named as the right child and left child.
这是一个类似于选项的容器,该容器具有两个值,它们被称为子级。 左边的孩子和右边的孩子分别命名为右边的孩子和左边的孩子 。
The left child is similar to None class which is used when there can be an error returned.
左子级类似于None类,该类可以在返回错误时使用。
The right child is similar to Some class which is used when a vale is to be returned i.e. for the successful execution of code.
正确的子级类似于Some类,该类将在返回谷时即成功执行代码时使用。
Syntax:
句法:
Either [left, right]
Both left and right are data types of the returned values which can be used to define the results when there are error case or valid case.
左和右均为返回值的数据类型,当出现错误情况或有效情况时,可用于定义结果。
理解任一关键字工作方式的示例 (Example to understand the working of Either Keyword)
object MyObject {
// function defintion
def isEven(number : Int ): Either[String, String] = {
if(number%2 == 0){
Right(number + " is even.")
}
else
Left(number + " is not even.")
}
// main code
def main(args: Array[String]) {
println(isEven(4))
println(isEven(95))
}
}
Output
输出量
Right(4 is even.)
Left(95 is not even.)
翻译自: https://www.includehelp.com/scala/either-keyword.aspx
scala语言示例