Scala基础语法学习笔记

scala学习笔记

脚本模式编程

object HelloWorld {
   def main(args: Array[String]) {
      println("Hello, world!") // prints Hello World
   }
}

基础语法
区分大小写 - Scala是大小写敏感的,这意味着标识Hello 和 hello在Scala中会有不同的含义。

类名 - 对于所有的类名的第一个字母要大写。

如果需要使用几个单词来构成一个类的名称,每个单词的第一个字母要大写。
示例:class MyFirstScalaClass
方法名称 - 所有的方法名称的第一个字母用小写。
如果若干单词被用于构成方法的名称,则每个单词的第一个字母应大写。
示例:def myMethodName()
程序文件名 - 程序文件的名称应该与对象名称完全匹配。
保存文件时,应该保存它使用的对象名称(记住Scala是区分大小写),并追加“.scala”为文件扩展名。 (如果文件名和对象名称不匹配,程序将无法编译)。
示例: 假设“HelloWorld”是对象的名称。那么该文件应保存为’HelloWorld.scala“
def main(args: Array[String]) - Scala程序从main()方法开始处理,这是每一个Scala程序的强制程序入口部分。
换行符:
语句可以用分号(;)结束或换行符。分号在声明的结尾通常是可选的。

变量声明

var myVar : String = "Foo"
var myVar = 10;
val myVal = "Hello, Scala!";
val (myVar1: Int, myVar2: String) = Pair(40, "Foo")

函数定义:

def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]
}
def addInt( a:Int, b:Int ) : Int = {
      var sum:Int = 0
      sum = a + b
      return sum
   }
void函数
   def printMe( ) : Unit = {
      println("Hello, Scala!")
   }
def main(args: Array[String]) {
        printInt(b=5, a=7);
   }
   def printInt( a:Int, b:Int ) = {
      println("Value of a : " + a );
      println("Value of b : " + b );
   }
def main(args: Array[String]) {
        printStrings("Hello", "Scala", "Python");
   }
   def printStrings( args:String* ) = {
      var i : Int = 0;
      for( arg <- args ){
         println("Arg value[" + i + "] = " + arg );
         i = i + 1;
      }
   }

匿名函数

var inc = (x:Int) => x+1
var x = inc(7)-1
var mul = (x: Int, y: Int) => x*y
println(mul(3, 4))

柯里函数

def strcat(s1: String)(s2: String) = s1 + s2
def strcat(s1: String) = (s2: String) => s1 + s2
strcat("foo")("bar")
对于date使用不同的message的值
def main(args: Array[String]) {
      val date = new Date
      val logWithDateBound = log(date, _ : String)


      logWithDateBound("message1" )
      Thread.sleep(1000)
      logWithDateBound("message2" )
      Thread.sleep(1000)
      logWithDateBound("message3" )
   }
   def log(date: Date, message: String)  = {
     println(date + "----" + message)
   }

定义数组

var z = Array("Zara", "Nuha", "Ayan")
concat()方法来连接两个数组的例子
var myList1 = Array(1.9, 2.9, 3.4, 3.5)
var myList2 = Array(8.9, 7.9, 0.4, 1.5)
var myList3 =  concat( myList1, myList2)

集合

// Define List of integers.链表
val x = List(1,2,3,4)
val fruit: List[String] = List("apples", "oranges", "pears")
val nums: List[Int] = List(1, 2, 3, 4)
// Define a set.不同元素的集合
var x = Set(1,3,5,7)
// Define a map.键/值对
val x = Map("one" -> 1, "two" -> 2, "three" -> 3)
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")
// Create a tuple of two elements.元组可以容纳不同类型的对象
val x = (10, "Scala")
val t = (1, "hello", Console)
// Define an option  Option[T] 提供了一种容器,用于给定类型的零个或一个元素
val x:Option[Int] = Some(5)
使用:::运算符或列表List.:::()方法或List.concat()方法来添加两个或多个列表
val fruit1 = "apples" :: ("oranges" :: ("pears" :: Nil))
val fruit2 = "mangoes" :: ("banana" :: Nil)
 var fruit = fruit1 ::: fruit2
 fruit = List.concat(fruit1, fruit2)
 创建统一列表包括相同的元素如下的零个或更多个拷贝的列表
 val fruit = List.fill(3)("apples") // Repeats apples three times.
 串联集合:
 val fruit1 = Set("apples", "oranges", "pears")
      val fruit2 = Set("mangoes", "banana")
      // use two or more sets with ++ as operator
      var fruit = fruit1 ++ fruit2
      println( "fruit1 ++ fruit2 : " + fruit )
      // use two sets with ++ as method
      fruit = fruit1.++(fruit2)
查找集合的共同值:
val num1 = Set(5,6,9,20,30,45)
      val num2 = Set(50,60,9,20,35,55)
      // find common elements between two sets
      println( "num1.&(num2) : " + num1.&(num2) )
      println( "num1.intersect(num2) : " + num1.intersect(num2) )

键值对添加到映射

A += ('I' -> 1)
A += ('J' -> 5)
映射的基本操作:
val colors = Map("red" -> "#FF0000","azure" -> "#F0FFFF","peru" -> "#CD853F")
      println( "Keys in colors : " + colors.keys )
      println( "Values in colors : " + colors.values )
串联映射
val colors1 = Map("red" -> "#FF0000",
                        "azure" -> "#F0FFFF",
                        "peru" -> "#CD853F")
      val colors2 = Map("blue" -> "#0033FF",
                        "yellow" -> "#FFFF00",
                        "red" -> "#FF0000")
      // use two or more Maps with ++ as operator
      var colors = colors1 ++ colors2
      println( "colors1 ++ colors2 : " + colors )


      // use two maps with ++ as method
      colors = colors1.++(colors2)
打印映射的键和值:
colors.keys.foreach{ i =>
                           print( "Key = " + i )
                           println(" Value = " + colors(i) )}
检查映射中的键:
colors.contains( "red" )
访问的元组 t 的元素
val t = (4,3,2,1)
val sum = t._1 + t._2 + t._3 + t._4

遍历元组:

val t = (4,3,2,1)
      t.productIterator.foreach{ i =>println("Value = " + i )}
Option[T]是容器对于给定的类型的零个或一个元件
模式匹配
def main(args: Array[String]) {
      val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
      println("show(capitals.get( "Japan")) : " +
                                          show(capitals.get( "Japan")) )
      println("show(capitals.get( "India")) : " +
                                          show(capitals.get( "India")) )
   }
     def show(x: Option[String]) = x match {
      case Some(s) => s
      case None => "?"
   }
使用getOrElse()来访问值或使用默认值
迭代器不是集合,而是一种由一个访问的集合之一的元素
next和hasNext
类
class Yiibai(val xc: Int, val yc: Int) {
   var x: Int = xc
   var y: Int = yc
   def move(dx: Int, dy: Int) {
      x = x + dx
      y = y + dy
      println ("Yiibai x location : " + x);
      println ("Yiibai y location : " + y);
   }
}
class Location(override val xc: Int, override val yc: Int,
   val zc :Int) extends Yiibai(xc, yc){
   var z: Int = zc


   def move(dx: Int, dy: Int, dz: Int) {
      x = x + dx
      y = y + dy
      z = z + dz
      println ("Yiibai x location : " + x);
      println ("Yiibai y location : " + y);
      println ("Yiibai z location : " + z);
   }
}
object Test {
   def main(args: Array[String]) {
      val loc = new Location(10, 20, 15);


      // Move to a new location
      loc.move(10, 10, 5);
   }
}

判断与循环

def main (args: Array[String]) {
    println("Hello, world!")
    var x = 30;
    if( x < 20 ){
      println("This is if statement");
    }else{
      println("This is else statement");
    }
    println(addInt(1,2));
    while( x < 32 ){//while循环的关键点是循环可能不会永远运行
      println( "Value of x: " + x );
      x += 1;
    }
    do{
      println( "Value of xx: " + x );
      x = x + 1;
    }while( x < 33 )


    var a = 0;
    // for loop execution with a range
    for( a <- 1 to 10){
      println( "Value of a: " + a );
    }
    for( a <- 1 until 10){
      println( "Value of a: " + a );
    }


    var b = 0;
    // for loop execution with a range
    for( a <- 1 to 3; b <- 1 to 3){
      println( "Value of a: " + a );
      println( "Value of b: " + b );
    }


    val numList = List(1,2,3,4,5,6);
    // for loop execution with a collection
    for( a <- numList ){
      println( "Value of a: " + a );
    }
    for( a <- numList
         if a != 3; if a < 8 ){
      println( "Value of a: " + a );
    }


    // for loop execution with a yield
    val retVal = for{ a <- numList
                      if a != 3; if a < 8
    }yield a
    // Now print returned values using another loop.
    for( a <- retVal){
      println( "Value of a: " + a );
    }
  }
  def addInt( a:Int, b:Int ) : Int = {
    var sum:Int = 0
    sum = a + b
    return sum
  }

模式匹配包括替代的序列,每个开始使用关键字case

 def main(args: Array[String]) {
      println(matchTest("two"))
      println(matchTest("test"))
      println(matchTest(1))
   }
   def matchTest(x: Any): Any = x match {
      case 1 => "one"
      case "two" => 2
      case y: Int => "scala.Int"
      case _ => "many"
   }
正则表达式
val pattern = "Scala".r   //调用r()方法 字符串隐式转换为一个RichString并调用该方法来获得正则表达式的一个实例

val str = "Scala is Scalable and cool"
println(pattern findFirstIn str)
val pattern = new Regex("(S|s)cala")  //a|b  匹配a或b。
val str = "Scala is scalable and cool"
println((pattern findAllIn str).mkString(","))
更换匹配的文本,可以使用replaceFirstIn()以取代第一个匹配项或replaceAllIn()
val pattern = "(S|s)cala".r
val str = "Scala is scalable and cool"
println(pattern replaceFirstIn(str, "Java"))
. 匹配除了换行符的任何字符
[Rr]uby 匹配 "Ruby""ruby"    [...]
匹配括号内任何单个字符。
rub[ye] 匹配"ruby""rube"
[aeiou] 匹配任何一个小写元音
[0-9] 匹配任何数字;同 [0123456789]
[a-z] 匹配任意小写ASCII字母
[A-Z] 匹配任意大写ASCII字母
[a-zA-Z0-9] 匹配任何上述
[^aeiou] 匹配元音以外的任何一个小写字符   [^...]
匹配任何单个字符不是在括号中
[^0-9] 匹配数字以外的任何其他
d 匹配一个数字: [0-9]
D 匹配一个非数字: [^0-9]
s 匹配一个空白字符: [ f]
S 匹配非空白: [^ f]
w 匹配一个字符: [A-Za-z0-9_]
W 匹配 一个非单词字符: [^A-Za-z0-9_]
ruby? 匹配 "rub" or "ruby": the y is optional  re?
匹配01发生前表达式。
ruby* 匹配 "rub" plus 0 or more ys
ruby+ 匹配 "rub" plus 1 or more ys
d{3} 匹配只有 3 个数字   d
匹配数字。相当于 [0-9]. re{ n} 精确匹配n个前面表达式的数量。
d{3,} 匹配 3 个或多个数字  re{ n,}
匹配n或多次出现前面的表达。
d{3,5} 匹配3, 4, 或5 个数字  re{ n, m}
至少匹配n和在前面的表现最为m次出现。
Dd+ 不分组: + repeats d   re+
匹配1个或多个的先前东西
(Dd)+/ 分组: + repeats Dd 对  D
匹配非数字。(re) 组正则表达式并记住匹配的文本
([Rr]uby(, )?)+ 匹配 "Ruby", "Ruby, ruby, ruby", 等

抛出异常

throw new IllegalArgumentException
try {
         val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException =>{
            println("Missing file exception")
         }

文件I/O

写入文件
val writer = new PrintWriter(new File("test.txt" ))
writer.write("Hello Scala")
writer.close()
从屏幕读取一行:
print("Please enter your input : " )
val line = Console.readLine
println("Thanks, you just typed: " + line)
读取文件内容
Source.fromFile("test.txt" ).foreach{
         print
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值