基础的scala语法和函数
package com.yjm.scala object Person { def main(args: Array[String]): Unit = { } var age = 20 if (age > 20) { println("可以观看欧美") } else if (age > 18) { println("可以看国产") } else { println("禁止观看") } var count = 1 while (count < 102) { println("第" + count + "次迟到") count += 1 } do { count -= 1 println("第" + count + "次迟到") } while (count > 1) println(1 to 10) println(1.to(10, 2)) //步长为2 println(1 until 10) println(1.until(10, 2)) //步长为2 //统计 1-100的和 var sum = 0 for (elem <- 1 to 100) { sum += elem } println(sum) //返回一个集合 val oss = for (i <- 1 to 100; if i % 2 == 0) yield i for (elem <- oss) { println(elem) } /** * 函数 */ def add(num1:Int,num2:Int):Int={ num1+num2 } println(add(1,2)) /** * 递归函数 */ def fun(num:Int):Int={ if(num==1){ num }else{ num*fun(num-1) } } println(fun(10)) /** * 默认参数的函数 */ def fun3(n1:Int=10,n2:Int)={ n1+n2 } println(fun3(n1=9,n2=100)) /** * 乘法表 */ for(i <- 1 to 9 ;j <- 1 to i){ print(i+"*"+j+"="+ j*i+"\t" ) if(j==i){ println() } } }
原文地址:https://www.cnblogs.com/yangjiming/p/9589021.html
时间: 2024-10-08 23:40:44