脚本语言

sql , js , shell , python
所见即所得.
repl        //read -> evalute -> print -> loop
               javac            java
java : *.java ------->*.class  ------->app

scala

java语句脚本化。

scala

1.下载2.11.8
2.安装
3.scala

scala>
1 + 1
1.+(1) //$plus

val //值类型,等价于java中常量
var //变量

//常量
val a = 1
a = 2 //wrong

//变量
var a = 1
a = 2 //ok

val a:Int = 1

//定义类型
val a:Int = 1
val a:Int = “abc” //wrong
val a:String = “abc”
val a:java.lang.String = “abc”

//同时初始化多个变量
val a,b = 1000

//
1.to(10)
1 to 10
1 == 1
1.==(1)

//字符串交集
“abc”.intersect(“bcd”);

//scala没有++ –,有+= -=

//java:方法和函数没区别
//scala:函数独立调用,不需要通过对象,方法通过对象调用
pow(3,3)

//java : import java.lang.*
//scala : import java.lang._

//import scala.math._
//幂函数
pow(2,2) //
pow(27,1.toFloat/3) //开立方

//平方根
sqrt(4,2);

//apply()
“hello”(4)
“hello”.apply(4)

//条件表达式
val x = 0 ;
var r = if(x > 1) 1 else -1 //Int
var r = if(x > 1) “1” else -1 //Any
var r = if(x > 1) “1” //else缺失,a:Unit = (),类似于null

//scala没有三元运算符 ? :

//换行问题
val r = if(x > 1) {1
}else -1

//粘贴模式
:paste

ctrl + D

//块的值
val r = {1 ;2;3;4} //4

//打印函数
println(“abc”)

//c风格打印
printf(“a=%d , b = %d , c= %s”, 1,2,”abc”)

//读取输入
var name = readLine(“please input your name: “)
printf(“your name is : %s\r\n” , name) ;

//while
var n = 1
while(n < 9){
println(n)
n += 1
}

for(x <- 1 to 10){
println(x)
}

//99表格
var r = 1 ;
while(r <= 9 ){
var c = 1 ;
while(c <= r){
printf(“%dx%d=%d\t”,c , r , (c * r))
c +=1
}
println()
r += 1
}

//99for循环
for(r <- 1 to 9){
for(c <- 1 to r){
printf(“%dx%d=%d\t”,c , r , (c * r))
}
println()
}

//while for实现百钱买百鸡
//100钱
//100鸡
// 5/公鸡 , 3/母鸡 1/3只小鸡

//to
1 to 10 //1 ~ 10
1 until 10 //1 ~ 9

//scala没有break 和 continue
import scala.util.control.Breaks._
for(x <- 1 to 10){println(x) ; break() ;}
for(x <- 1 to 10){println(x) ; continue ;}

//高级for循环,笛卡尔积
for(x <- 1 to 3 ; y <- 1 to 3){printf(“x=%d,y=%d\r\n”, x,y)}

//守卫条件
for(x <- 1 to 3 if x > 1 ; y <- 1 to 3 if x != y){printf(“x=%d,y=%d\r\n”, x,y)}

//yield,产生,生成,for循环推导式
for(x <- 1 to 4) yield x.toString

//计算阶乘,递归函数需要显式定义返回值类型
def fac(n:Int):Int= {if (n == 1) 1 else n * fac(n- 1);}

//带名参数和默认参数
def decorate(pre:String=”<<<”,str:String , suf:String=”>>>”) = pre + str = suf
decorate(str=”hello”)
decorate(str=”hello”,pre=”{{{“)

//变长参数
def sum(a:Int*) = {var s = 0 ; for(x <- a) s += x ; s}

//定义函数
def add(a:Int,b:Int) = a + b
def add(a:Int,b:Int):Int = a + b

//scala中的_用法
1.导包统配,等价于java中的*
import scala.math._

2.将Range对象转换成序列
    1 to 10:_*
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐