groovy的switch/case判断

Posted benhuli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了groovy的switch/case判断相关的知识,希望对你有一定的参考价值。

switch/case

 1 //java中switch只能传入int类型、byte,char和short类型能自动提升为int类型、String类型和后来扩展的enum类型
 2 
 3 //在groovy中,switch可以传入任性类型的数据进行匹配
 4 String judgeType(Object x) {
 5     def result
 6     switch (x) {
 7         case "string":
 8             result = "x is string"
 9             break
10         case [4, 5, 6, 7,‘inList‘]: //列表(数据结构中讲解)
11             result = "x is in list [4, 5, 6, 7,‘inList‘]"
12             break
13         case 10..15: //范围range(数据结构中讲解)
14             result = "x is in range 10..15"
15             break
16         case Integer:
17             result = "x is Integer"
18             break
19         case BigDecimal:
20             result = "x is BigDecimal"
21             break
22         case List:
23             result = "x is List"
24             break
25         default:
26             result = "no match"
27             break
28     }
29     return result
30 }
31 
32 def x = "string"
33 def x1 = 5
34 def x2 = 10
35 def x3 = 3
36 def x4 = 3.14
37 def x5 =[4,6]
38 def x6 ="hi groovy"
39 def x7 = "inList"
40 println judgeType(x) //x is string
41 println judgeType(x1) // x is in list [4, 5, 6, 7,‘inList‘]
42 println judgeType(x2) // x is in range 10..15
43 println judgeType(x3) // x is Integer
44 println judgeType(x4) // x is BigDecimal
45 println judgeType(x5) // x is List
46 println judgeType(x6) // no match
47 println judgeType(x7) // x is in list [4, 5, 6, 7,‘inList‘]

 

以上是关于groovy的switch/case判断的主要内容,如果未能解决你的问题,请参考以下文章

switch case的用法

switch case的用法

Java switch case语句

switch case语句和if的区别

给出一种较好的替换switch case的方法 除了map映射还有么

java中switch case怎么表示范围