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']

猜你喜欢

转载自www.cnblogs.com/benhuli/p/11883678.html