- var nums = [5, 7, 3, 9];
- var total = {
- var sum = 0;
- for (a in nums) { sum += a };
- sum;
- }
- println("Total is {total}."); // Total is 24
The if Expression
- def age = 8;
- var ticketPrice;0
- if (age < 5 ) {
- ticketPrice = 0;
- } else if (age < 12 or age > 65) {
- ticketPrice = 5;
- } else {
- ticketPrice = 10;
- }
- println("Age: {age} Ticket Price: {ticketPrice} dollars.");
次のように1行で書くことも可能
- ticketPrice = if (age < 5) 0 else if (age > 5 and age < 12) 5 else 10;
Range Expressions
- var num = [0..5];
- var nums = [1..10 step 2]; // [ 1, 3, 5, 7, 9 ]
- var nums = [10..1 step -1];
- // [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
The for Expression
- var days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"];
- for (day in days) {
- println(day);
- }
- // Resulting sequence squares the values from the original sequence.
- var squares = for (i in [1..10]) i*i;
- // Resulting sequence is ["MON", "TUE", "WED", and so on...]
- var capitalDays = for (day in days) day.toUpperCase();
The while Expression
- var count = 0;
- while (count < 10) {
- println("count == {count}");
- count++;
- }
The break and continue Expressions
- for (i in [0..10]) {
- if (i > 5) {
- break;
- }
- if (i mod 2 == 0) {
- continue;
- }
- println(i);
- }
The throw, try, catch and finally Expressions
- try {
- foo();
- } catch (e: Exception) {
- println("{e.getMessage()} (but we caught it)");
- } finally {
- println("We are now in the finally expression...");
- }
- function foo() {
- var somethingWeird = false;
- if(somethingWeird){
- throw new Exception("Something weird just happened!");
- } else {
- println("We made it through the function.");
- }
- }
0 件のコメント:
コメントを投稿