微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐