Scala入门基础1

1》元组

元组的定义,元组的最大长度为22

 
val pa=(3,4,"hellow")
 

 定义元组是可以定义类型若无则自动选择类型

 
val pa:(Int,String)=(20,"fpp")

遍历输出

pa.productIterator.foreach{
  i=>print("value="+i)
}

访问指定位置元素(访问第一个元素)

 
println(pa._1)
 

元组元素位置交换(仅限两个元素)

 
println(pa.swap)
 

2》访问修饰符

private

用 private 关键字修饰,带有此标记的成员仅在包含了成员定义的类或对象内部可见,同样的规则还适用内部类。

protected

在 scala 中,对保护(Protected)成员的访问比 java 更严格一些。因为它只允许保护成员在定义了该成员的的类的子类中被访问,而一个包下不允许访问。

public

Scala中,如果没有指定任何的修饰符,则默认为 public。这样的成员在任何地方都可以被访问

作用域

private[x] 

或 

protected[x]

x指代某个所属的包、类或单例对象
 

3》运算符

位运算符用来对二进制位进行操作,~,&,|,^分别为取反,按位与与,按位与或,按位与异或运算,如下表实例:

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

A = 0011 1100

<< 左移动运算符 a << 2 输出结果 240 ,二进制解释: 1111 0000
>> 右移动运算符 a >> 2 输出结果 15 ,二进制解释: 0000 1111
>>> 无符号右移 A >>>2 输出结果 15, 二进制解释: 0000 1111

计算过程中会自动转换为二进制

例:

 
var a = 3
var b = 10
var c=0
c=a & b
print("a&&b="+c)

输出:a&&b=2
 

符号优先级

类别 运算符 关联性
1 () [] 左到右
2 ! ~ 右到左
3 * / % 左到右
4 + - 左到右
5 >> >>> << 左到右
6 > >= < <= 左到右
7 == != 左到右
8 & 左到右
9 ^ 左到右
10 | 左到右
11 && 左到右
12 || 左到右
13 = += -= *= /= %= >>= <<= &= ^= |= 右到左
14 , 左到右

http://www.runoob.com/scala/scala-operators.html

4》循环

while与do...while与java差距不大

for循环

//使用to,从1到10循环,输出12345678910

 
for (a <- 1 to 10){
  println(a);
}

//使用until,从1到10循环,输出123456789

 
for( a <- 1 until 10){
  println( "Value of a: " + a );
}

//多个循环,如下会循环6次

 
for( a <- 1 to 2; b <- 1 to 3){
  println( "Value of a: " + a );
  println( "Value of b: " + b );
}

输出

  Value of a: 1
  Value of b: 1
  Value of a: 1
  Value of b: 2
  Value of a: 1
  Value of b: 3
  Value of a: 2
  Value of b: 1
  Value of a: 2
  Value of b: 2
  Value of a: 2
  Value of b: 3

循环集合

  var a = 0;
  val numList = List(1,2,3,4,5,6);

  // for 循环
  for( a <- numList ){
    println( "Value of a: " + a );
  }
}

循环过滤

 
for( a <- numList if(a%2)==0){}
 

yield保存数据,将数据a*2保存到了reVal中

 
val numList = List(1,2,3,4,5,6);

// for 循环
var retVal = for{ a <- numList
                  if(a%2)==0
}yield a*2

for( a <- retVal){
  println( "Value of a: " + a );
}

5》方法

定义函数如下,若不加=和方法主体默认为抽象函数,若无返回类型则将第三个Int换为Unit(相当于void)

 
def addInt(a:Int,b:Int):Int={
  return a+b
}

函数调用

多个参数的函数

 
def main(args: Array[String]) {
  printStrings("Runoob", "Scala", "Python")
}
  def printStrings( args:String* ) = {
    var i : Int = 0;
    for( arg <- args ){
      println("Arg value[" + i + "] = " + arg );
      i = i + 1;
    }
  }

添加默认参数的函数

 
def main(args: Array[String]) {
  println( "返回值 : " + addInt(4) );
}
def addInt( a:Int=5, b:Int=7 ) : Int = {
  return sum
}

内嵌函数

 
def factorial(i: Int): Int = {
  def fact(i: Int, accumulator: Int): Int = {
    if (i <= 1)
      return accumulator
    else
      return fact(i - 1, i * accumulator)
  }
  fact(i, 1)
}

匿名函数,如下代码第二行相当于之前的add函数也是两个数求和

 
def main(args: Array[String]) {
 var add=(x:Int,y:Int)=>x+y;
  print(add(4,5))
}
函数:http://www.runoob.com/scala/scala-functions.html

6》闭包

在函数中使用函数以外的变量,定义这个函数的过程是将这个自由变量捕获而构成一个封闭的函数,如下输出结果为19

 
var v=10;
var add=(x:Int,y:Int)=>x+y+v;
print(add(4,5))

7》字符串

创建格式化字符串

var floatVar = 12.456
var intVar = 2000
var stringVar = "wangHY!"
var fs = printf("浮点型变量为%f 整型变量为 %d, 字符串为%s", floatVar, intVar, stringVar)

//var fs = printf("浮点型变量为 " +
  "%f, 整型变量为 %d, 字符串为 " +
  " %s", floatVar, intVar, stringVar)

println(fs)
 
序号 方法及描述
1

char charAt(int index)

返回指定位置的字符

2

int compareTo(Object o)

比较字符串与对象

3

int compareTo(String anotherString)

按字典顺序比较两个字符串

4

int compareToIgnoreCase(String str)

按字典顺序比较两个字符串,不考虑大小写

5

String concat(String str)

将指定字符串连接到此字符串的结尾

6

boolean contentEquals(StringBuffer sb)

将此字符串与指定的 StringBuffer 比较。

7

static String copyValueOf(char[] data)

返回指定数组中表示该字符序列的 String

8

static String copyValueOf(char[] data, int offset, int count)

返回指定数组中表示该字符序列的 String

9

boolean endsWith(String suffix)

测试此字符串是否以指定的后缀结束

10

boolean equals(Object anObject)

将此字符串与指定的对象比较

11

boolean equalsIgnoreCase(String anotherString)

将此 String 与另一个 String 比较,不考虑大小写

12

byte getBytes()

使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中

13

byte[] getBytes(String charsetName

使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中

14

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

将字符从此字符串复制到目标字符数组

15

int hashCode()

返回此字符串的哈希码

16

int indexOf(int ch)

返回指定字符在此字符串中第一次出现处的索引

17

int indexOf(int ch, int fromIndex)

返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索

18

int indexOf(String str)

返回指定子字符串在此字符串中第一次出现处的索引

19

int indexOf(String str, int fromIndex)

返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始

20

String intern()

返回字符串对象的规范化表示形式

21

int lastIndexOf(int ch)

返回指定字符在此字符串中最后一次出现处的索引

22

int lastIndexOf(int ch, int fromIndex)

返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索

23

int lastIndexOf(String str)

返回指定子字符串在此字符串中最右边出现处的索引

24

int lastIndexOf(String str, int fromIndex)

返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索

25

int length()

返回此字符串的长度

26

boolean matches(String regex)

告知此字符串是否匹配给定的正则表达式

27

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等

28

boolean regionMatches(int toffset, String other, int ooffset, int len)

测试两个字符串区域是否相等

29

String replace(char oldChar, char newChar)

返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的

30

String replaceAll(String regex, String replacement

使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串

31

String replaceFirst(String regex, String replacement)

使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串

32

String[] split(String regex)

根据给定正则表达式的匹配拆分此字符串

33

String[] split(String regex, int limit)

根据匹配给定的正则表达式来拆分此字符串

34

boolean startsWith(String prefix)

测试此字符串是否以指定的前缀开始

35

boolean startsWith(String prefix, int toffset)

测试此字符串从指定索引开始的子字符串是否以指定前缀开始。

36

CharSequence subSequence(int beginIndex, int endIndex)

返回一个新的字符序列,它是此序列的一个子序列

37

String substring(int beginIndex)

返回一个新的字符串,它是此字符串的一个子字符串

38

String substring(int beginIndex, int endIndex)

返回一个新字符串,它是此字符串的一个子字符串

39

char[] toCharArray()

将此字符串转换为一个新的字符数组

40

String toLowerCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为小写

41

String toLowerCase(Locale locale)

使用给定 Locale 的规则将此 String 中的所有字符都转换为小写

42

String toString()

返回此对象本身(它已经是一个字符串!)

43

String toUpperCase()

使用默认语言环境的规则将此 String 中的所有字符都转换为大写

44

String toUpperCase(Locale locale)

使用给定 Locale 的规则将此 String 中的所有字符都转换为大写

45

String trim()

删除指定字符串的首尾空白符

46

static String valueOf(primitive data type x)

返回指定类型参数的字符串表示形式

 

7》数组

数组的创建和遍历

  var myList=Array(1,5,2,3,8,5,2,14);
    //var z = new Array[String](3)
    for(x <- myList){
      print(x+" ")
    }

 二维数组

import Array._
object HelloWorld
{

  def main(args: Array[String]) {
    var myMatrix = ofDim[Int](3,3)
    for(i <-0 to 2){
      for(j <- 0 to 2){
        myMatrix(i)(j)=i+j;
      }
    }
    for (i <- 0 to 2) {
      for ( j <- 0 to 2) {
        print(" " + myMatrix(i)(j));
      }
      println();
    }
  }

}

 数组相加

   var list1=Array(1,5,2)
  var list2=Array(3,4,5) var list3=concat(list1,list2)// list3为152345

区间数组

var list1=range(0,20,2)//024681012141618
var list2=range(0,20,4)//0481216
序号 方法和描述
1

def apply( x: T, xs: T* ): Array[T]

创建指定对象 T 的数组, T 的值可以是 Unit, Double, Float, Long, Int, Char, Short, Byte, Boolean。

2

def concat[T]( xss: Array[T]* ): Array[T]

合并数组

3

def copy( src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int ): Unit

复制一个数组到另一个数组上。相等于 Java's System.arraycopy(src, srcPos, dest, destPos, length)。

4

def empty[T]: Array[T]

返回长度为 0 的数组

5

def iterate[T]( start: T, len: Int )( f: (T) => T ): Array[T]

返回指定长度数组,每个数组元素为指定函数的返回值。

以上实例数组初始值为 0,长度为 3,计算函数为a=>a+1

scala> Array.iterate(0,3)(a=>a+1) res1: Array[Int] = Array(0, 1, 2)
6

def fill[T]( n: Int )(elem: => T): Array[T]

返回数组,长度为第一个参数指定,同时每个元素使用第二个参数进行填充。

7

def fill[T]( n1: Int, n2: Int )( elem: => T ): Array[Array[T]]

返回二数组,长度为第一个参数指定,同时每个元素使用第二个参数进行填充。

8

def ofDim[T]( n1: Int ): Array[T]

创建指定长度的数组

9

def ofDim[T]( n1: Int, n2: Int ): Array[Array[T]]

创建二维数组

10

def ofDim[T]( n1: Int, n2: Int, n3: Int ): Array[Array[Array[T]]]

创建三维数组

11

def range( start: Int, end: Int, step: Int ): Array[Int]

创建指定区间内的数组,step 为每个元素间的步长

12

def range( start: Int, end: Int ): Array[Int]

创建指定区间内的数组

13

def tabulate[T]( n: Int )(f: (Int)=> T): Array[T]

返回指定长度数组,每个数组元素为指定函数的返回值,默认从 0 开始。

以上实例返回 3 个元素:

scala> Array.tabulate(3)(a => a + 5) res0: Array[Int] = Array(5, 6, 7)
14

def tabulate[T]( n1: Int, n2: Int )( f: (Int, Int ) => T): Array[Array[T]]

返回指定长度的二维数组,每个数组元素为指定函数的返回值,默认从 0 开始。

 

猜你喜欢

转载自www.cnblogs.com/837634902why/p/10466521.html