scala case语句

Scala supports inbuilt pattern matching mechanism which is one of the more powerful feature. Pattern matching starts with the keyword case. Each includes a pattern or one or more expression that shall be evaluated if the pattern matches. An arrow symbol => separates pattern from the expressions.

Scala支持内置模式匹配机制,这是更强大的功能之一。 模式匹配以关键字case开头。 每个都包含一个模式或一个或多个表达式,如果模式匹配,则应对其进行评估。 箭头符号=>将模式与表达式分开。

Lets us consider a simple example of how to match against an integer value.

让我们考虑一个简单的示例,该示例如何与整数值进行匹配。

object Stud {def main(args:Array[String]) {
println(studAgematch(7))
println(studAgematch(5))
println(studAgematch(12))
}def studAgematch(age:Int) : String = age match {case 5 => "Student Age is 5 "
case 7 => "Student Age is 7"
case 8 => "Student Age is 8"
case 10 => "Student Age is 10"
case _ => "Student age is greater than 10"
}
}

We created the object Stud and defined the method main and invoked studAgematch method by passing an Integer argument. The studAgematch method accepts an Integer argument age, defines various cases for ages 5,7,8,10 and other numbers and prints the statements enclosing the case. We are passing numbers 7,5 ,12 and hence the case matching these numbers are printed.

我们创建了对象Stud并定义了main方法,并通过传递Integer参数调用了studAgematch方法。 studAgematch方法接受一个I​​nteger参数age,为age 5,7,8,10和其他数字定义各种大小写,并打印包含该大小写的语句。 我们正在传递数字7,5,12,因此将匹配这些数字的情况打印出来。

Run the program by typing Stud.main(null) and you will see below output in Scala shell.

通过键入Stud.main(null)运行程序,您将在Scala shell中看到以下输出。

scala> Stud.main(null)
Student Age is 7
Student Age is 5
Student age is greater than 10

In the above example we saw the cases for Integer data types but pattern matching can be done for string arguments as well.
Let us see an example for this below.

在上面的示例中,我们看到了Integer数据类型的情况,但是也可以对字符串参数进行模式匹配。
让我们在下面看到一个例子。

object Student {def main(args: Array[String]) {
println(matchAge("eight"))
println(matchAge("twelve"))
println(matchAge(7))
println(matchAge(9))
}def matchAge(age: Any): Any = age match {
case 7 => "Age is Seven"
case "eight" => 8
case y: Int => "Age is greater than 7"
case _ => "Age is greater than 10"
}
}

We created object Student with main method and invoked the matchAge method by passing the arguments with both string and integer data types. In the matchAge method, the first case is satisfied if the integer value is 7 and case y is executed if the integer value is other than 7. The second case with string “eight” is executed if the passed argument is of string value “eight” and for other default string values the case_ is executed.

我们使用main方法创建了Student对象,并通过传递带有字符串和整数数据类型的参数来调用matchAge方法。 在matchAge方法中,如果整数值为7,则满足第一种情况,如果整数值不是7,则满足y。如果传递的参数的字符串值为“八”,则执行具有字符串“八”的第二种情况。 ”,对于其他默认字符串值,执行case_。

Run the code by typing Student.main(null) and you will see below output.

通过键入Student.main(null)运行代码,您将看到以下输出。

scala> Student.main(null)
8
Age is greater than 10
Age is Seven
Age is greater than 7

使用案例类进行模式匹配 (Pattern Matching using case classes)

Scala supports case classes that can be used for pattern matching with case expressions. These classes are standard classes with a modifier case.

Scala支持案例类,可用于案例表达式的模式匹配。 这些类是带有修饰符大小写的标准类。

Let us understand this concept through an example;

让我们通过一个例子来理解这个概念;

object Stu {def main(args: Array[String]) {
val st1 = new Student(1,"Adam", 12)
val st2 = new Student(2,"John", 9)
val st3 = new Student(3,"Reena", 16)for (st <- List(st1, st2, st3)) {st match {
case Student(1,"Adam", 12) => println("Hello Adam")
case Student(3,"Reena", 16) => println("Hello Reena")
case Student(id,name, age) =>
println("Id: " + id + " Age: " + age + " Name: " + name)
}
}
}case class Student(id:Int, name: String, age: Int)
}

We create an object Stu with main method and create new student objects st1, st2 and st3. Using the for loop iterate through the list with objects st1, st2, st3 and st4 and use the case expressions with Student constructor by passing the values.

我们使用main方法创建一个对象Stu,并创建新的学生对象st1,st2和st3。 使用for循环使用对象st1,st2,st3和st4遍历列表,并通过传递值将case表达式与Student构造函数一起使用。

In the first case matching expression is the object Adam and second is for the name Reema and for other values the details are printed as specified in the last case. The student constructor is specified with id, name and age parameters for empty one.

在第一种情况下,匹配的表达式是对象Adam,第二种是名称Reema,对于其他值,则按照最后一种情况的指定打印详细信息。 指定学生构造函数的ID,名称和年龄参数为空。

Run the above code by typing Stu.main(null) and you will see below output.

通过键入Stu.main(null)运行以上代码,您将看到以下输出。

scala> Stu.main(null)
Hello Adam
Id: 2 Age: 9 Name: John
Hello Reena

Some quick points about the case classes pattern matching;

有关案例类模式匹配的一些要点;

  • The case keyword tells the compiler to add additional features automatically.case关键字告诉编译器自动添加其他功能。
  • The compiler automatically converts the constructor arguments into immutable fields. The val keyword is optional. If mutable fields are needed the var keyword can be used. The compiler implements equals, hashcode and toString methods using the fields specified as constructor arguments.编译器自动将构造函数参数转换为不可变字段。 val关键字是可选的。 如果需要可变字段,则可以使用var关键字。 编译器使用指定为构造函数参数的字段实现equals,hashcode和toString方法。

That’s all for now, we will look into more Scala features in coming posts.

到此为止,我们将在以后的文章中研究更多Scala功能。

翻译自: https://www.journaldev.com/7830/scala-pattern-matching-with-case-statement

scala case语句

scala case语句_Scala模式与case语句匹配相关推荐

  1. PHP中switch条件语句的使用,php条件语句(2)switch...case语句

    PHP 中的Switch语句用于执行基于多个不同条件的不同动作. Switch 语句 如果我们希望有选择地执行若干代码块之一,请使用 Switch语句. 使用 Switch语句可以避免冗长的if..e ...

  2. 逻辑判断-if语句/文件目录属性判断/case判断

    逻辑判断IF -gt :大于 -lt :小于 -eq :等于 -ne :不等于 -ge :大于或等于 -le :小于或等于 格式1: if 条件 :then 语句: fi a=5 if [ $a -g ...

  3. php switch case 判断语句,PHP的switch判断语句的“高级”用法详解,switch详解_PHP教程...

    PHP的switch判断语句的"高级"用法详解,switch详解 只所以称为"高级"用法,是因为我连switch的最基础的用法都还没有掌握,so,接下来讲的其实 ...

  4. 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)

    求1+2+3+-+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C) 文章目录 求1+2+3+...+n,要求不能使用乘除法.for ...

  5. shell编程之条件语句(文件测试,test命令,字符串和逻辑测试,if单支语句,if双支语句,if多支语句,case命令,用if写跑步小实验)

    文章目录 shell编程之条件语句 条件测试 test命令 整数值测试 free -m 提供了更简洁的查看系统内存使用情况: 字符串和逻辑测试 字符串 逻辑测试 一元运算符,二元运算符和三元运算符 i ...

  6. sql语句 case_使用SQL Case语句查询数据

    sql语句 case The Case statement in SQL is mostly used in a case with equality expressions. The SQL Cas ...

  7. 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

    求1+2+3+...+n,要求不能使用乘除法.for.while.if.else.switch.case等关键字及条件判断语句(A?B:C). //利用构造函数求解 /*class Temp{ pub ...

  8. oracle的switch+case语句吗,2.7 switch 语句中的 case 范围

    2.7 switch 语句中的 case 范围 在标准 C 中,switch 语句中的 case 标签只能有一个关联值.Solaris Studio C 允许使用某些编译器中使用的扩展(称为 case ...

  9. Verilog语言之结构语句:if、case

    if语句 一个if语句通常可以创造出一个2选1选择器,当条件为真时选择一个输入,为假时选择另一个. always @(*) beginif (condition) beginout = x;endel ...

最新文章

  1. 1.3. redis-cli - Command-line client to redis-server
  2. 【安全技术】红队之windows信息收集思路
  3. bilibili怎么设置弹幕数量_python爬虫:bilibili弹幕爬取+词云生成
  4. CM: 如何通过table SKWG_BREL快速查询product attachment信息
  5. endnote x9中科大版_文献管理软件Endnote的一些使用经验
  6. android 蒙层广告1,subnvue安卓机打开只显示蒙层,没有任何内容【报Bug】
  7. 登录或连接MYSLQ 提示 error 1045 access denied for user 'root@127.0.0.1' 错误
  8. Python模拟浏览器向 CSDN发送POST请求的方法
  9. 集成学习:Boosting与Bagging
  10. pandas(python2) 读取中文数据,处理中文列名
  11. 21. 面向服务的体系架构(SOA)
  12. 搭积木php编程,Primo Toys,一款可以同时搭积木与编程的玩具
  13. 顺着IP地址他们能找到我家吗?
  14. matlab中readfid函数,matlab中textscan和textread函数的比较使用
  15. centOS7安装redis单例配置主从+哨兵+VIP
  16. 商务网站建设与维护【6】
  17. gensim中word2vec API参数说明
  18. 面试面经 | 2021大疆嵌入式软件工程师笔试题B卷
  19. myeclipse8.5 TPTP插件的使用问题
  20. cdr 表格自动填充文字_当文字内容太多excel单元格盛不下应该怎么做

热门文章

  1. 数据库的Timeout
  2. 2nbsp;时间管理和内存管理
  3. Alarm:IT界朋友请珍惜你的身体[转贴]
  4. [转载] Python time sleep()方法如何使用?
  5. 【LeetCode】28. Implement strStr()
  6. 深度学习基础(基础知识0)
  7. javascript中的对象之间继承关系
  8. AWK处理日志入门(转)
  9. x201 温度过高 反应慢 硬盘搜索时更慢更热 为什么呢?
  10. 【学习OpenCV4】滚动条Trackbar的创建与使用详解