scala 一些知识整理

前言:

1 下载地址: www.scala-lang.org

2 这里下载的是 scala-2.11.1.msi, 本身就可以在window上运行,

安装时要指定最好不要将scala安装到带有空格的路径,否则可能在运行“scala”命令的时候报“此时不应有 \scala\bin\scala.bat)。”的错误提示。

3 关于 idea支撑scala的配置,见 idea 集成 maven和scala.note

4 使用版本介绍:

scala版本:2.10.4 后面的spark也对应的scala这个版本, 最新版本 2.12.3

idea版本 14.1.1 ideaIC-14.1.1.exe

maven 版本3.3.3

扫描二维码关注公众号,回复: 302299 查看本文章

jdk版本: 1.7

scala默认导入的三个包:

import java.lang._

import scala._

import Predef._

scala思想都是对象,因此没有基本数据类型, scala比Java面向对象更彻底,没有基础类型, scala奇妙的地方, 一切都是对象

scala 集合collection分为可变和不可变两种,

scala.collection.mutable

scala.collection.immutable

其中,默认创建的集合都是immutable collection types ,里面的集合都是定长、

scala的变量和常量赋值介绍:

scala语法是弱类型类似于js

一个是变量类型

一个是数值类型

scala变量定义:

scala>var a = 1 类型会根据值自动推断

a: Int = 1

scala>var b = "hello" 类型会根据值自动推断, 注意只能是"" 不能是''

b: String = hello

常量定义:

scala>val c = 10 给常量复制后就不能再修改值了

c: Int = 10

在scala中是不允许只声明但是不给初始化赋值的, 如下例子,第一次只是定义了变量 a,但是没有赋值,在scala命令行中 var a 后会继续等待你输入,



 

scala 好玩的样子
scala> var a=5
scala> var b="hello"
scala> a + b
res4: String = 5 hello ----> scala中 允许*是一个方法名的, String类型有一个*的方法, 比如写成 b.*(a)
scala> b*a


 
  在命令行中执行 scala :
HelloWorld.scala文件, 执行方式:
1 先编译,在执行, scalac HelloWorld.scala scala HelloWorld
2 直接执行 scala HelloWorld.scala
 
在配置了window机器的环境变量后,命令行cmd重启,就会把path重新加载一次。
 
在定义null的时候,只能是对var 变量来定义。

 
scala中调用Java类时,默认的Scala只会编译 这里目录的文件
<build>
<sourceDirectory> src/main/scala </sourceDirectory>
<testSourceDirectory> src/test/scala </testSourceDirectory>
<plugins>
 
如果scala文件中调用Java类,那么 可以手动将 这个Java类放在上面路径下让被编译到。
  scala导包, 用_ 而不用* 比如写法如下:
import java.util.Arrays._
  下面案例中 使用的 pom.xml如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ibeifeng.scala</groupId>
  <artifactId>scala_demo2</artifactId>
  <version>1.0-SNAPSHOT</version>
  <inceptionYear>2008</inceptionYear>
  <properties>
    <!-- 修改Scala的版本 -->
    <scala.version>2.10.4</scala.version>
  </properties>

  <repositories>
    <repository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>scala-tools.org</id>
      <name>Scala-Tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>
    <dependency>
      <groupId>org.specs</groupId>
      <artifactId>specs</artifactId>
      <version>1.2.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
          <args>
            <arg>-target:jvm-1.5</arg>
          </args>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <configuration>
          <downloadSources>true</downloadSources>
          <buildcommands>
            <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
          </buildcommands>
          <additionalProjectnatures>
            <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
          </additionalProjectnatures>
          <classpathContainers>
            <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
            <classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
          </classpathContainers>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <configuration>
          <scalaVersion>${scala.version}</scalaVersion>
        </configuration>
      </plugin>
    </plugins>
  </reporting>
</project>
     
scala  Array知识点整理:

1 定义数组两个方式:
   var a = new Array[Int](3) , []中是数据类型(可以去掉),()中是数组长度 表示定义长度为3的一个数组
   var a = Array[Int](1,2,3,4)   不使用new定义数组时,[]中是数据类型(可以去掉),()中初始化数组的值,表示这个数组里值为 3,4,5,6

数组: Array
变长数组: ArrayBuffer

++= 是增加数组的 
--= 减少数组
定长数组.toBuffer 变长变长数组

数组是以下标0开始的  var a = ArrayBuffer(1,2,3,4)
变长数组增加字段:  a+=5  a.insert(1,11)
变长数组修改字段  a(0) = 0 
变长数组删除字段: a-=3  会直接将里面元素为3的删除掉

数组迭代:
var b = for(tmp <- a if(tmp%2==0)) yeild tmp
 b.foreach(println)
 
数组排序:
a.sorted


--------------------------------------------------------------------------------

for  break continue:

定义函数:
  def demo02(): Unit = {...} 注意Unit可以理解为void, 如果函数是要返回值的,def demo02(): Int = {...函数最后一行为返回值}



i <- a to b 表示范围    [a,b]  for循环  for(tmp <- 0 until length)
i <- a until b 表示范围  [a,b) for循环  

for的推导式: for(tmp <- a.reverse) 
for的守位:  for(tmp <- a.reverse; if tmp %2 == 0)     for(tmp <- 0 to (length,2)) 2表示步长 
for增加break :  var _break = new Breaks  _break.breakable {for循环{if(xxx){_break.break()}}}  _break.breakable需要整个包住for循环
for中的continue:  var _break = new Breaks  for循环{_break.breakable {if(xxx){_break.break()}}}  _break.breakable仅需要包住在要跳出的地方

--------------------------------------------------------------------------------


List :

定义的两种方式:
 var list1 = List(1,2,3,4)  或者 var list2 = 0::1::2::3::Nil   list2 = list2 :+ 4
var list1 =  new ListBuffer[Int] list1 += 1  


--------------------------------------------------------------------------------


元组:
// 元组定义, 里面可以有多个数值类型 , 在获取的时候 用 _1 _2 _3这种方式获取 并且下标从1开始
def test2(): Unit = {
  var p1 = ("hello", 33, 19)
  println(p1._1  )
}

--------------------------------------------------------------------------------

case match   +  模式匹配 

// 模式匹配的值匹配 增加首位_ 这个占位符
  def test3(): Unit = {
    val a = 3
    val b = a match{ // _可以理解为占位符,表示参数a有多个值的时候,那么用_表示多个 如果a就一个值 比如 4那么直接写出4即可
      case _ if a>=0 && a<4  => "小于4"
      case   4 =>"等于4"
      case _ => "大于4"
    }
    print(b)
  }

// 模式匹配的类型匹配
def test4(): Unit = {
  val num:Any="1"
  num match {
    case i:Int => println("this is Int")
    case s:String => println("this is String")
    case _ => print("this is not Int and String, is other")
  }

}


  // 数组的模式匹配
  def test5(): Unit = {
    val array = Array(1,2,3)

    array match {
      case Array(1,2) => println("Array(1,2)")
      case Array(1,2,_) => println("Array(1,2,_) 三个参数")
      case Array(1,2,_*) => println("Array(1,2,_*) 三个以上参数")
      case _ => print("不识别")
    }

  }

--------------------------------------------------------------------------------

map:
 
1 定义: var map1 = Map("zhangsan"->23,"lisi"->32)   map1.getOrElse("zhangsan1","no having")  
2 增加元素: map1+=("wangwu"->33)
3 删除元素: map1-=("zhangsan")
4 修改元素; map1("lisi")=40
5 遍历: for((k,v) <- map1) for(tmp <- map1) for( k <- map1.keys)  for( v <- map1.values) 

--------------------------------------------------------------------------------

自定义函数和集合的 map()方法使用,  

集合的map()方法就是将 集合中的每一个元素 打散后来一个个处理

1 自定义函数:
 def mytoupcase(a:String): String ={
    a.toUpperCase()
  }
  
  
  
    // 定义函数 可变参数,  *表示有多个参数
  def sum1(x:Int*): Int = {
    var c = 0
    for(a<-x) {
      c=c+a
    }
    return c // return 可以有 可以不写, 定义的函数中,最后一行表示返回值
  }


2 集合的map()方法 :  此方法会把集合的所有元素得到并进行处理
var list = List("a" ,"b","c")
var newList = list.map(_.toUpperCase) // _表示集合所有元素

// 隐式调用
var newList = list.map(mytoupcase)  //  调用集合的map函数,在函数中因为集合就一个个的元素,因此在传递给自定义函数mytoupcase时直接省略传参
// 显示调用 
var newList = list.map(tmp => mytoupcase(tmp))


 // 定义函数,实现字母大写
  def mytoupcase(a:String): String ={
    a.toUpperCase()
  }

--------------------------------------------------------------------------------

集合rededuce() 方法 :

 // reudceleft : 集合元素从左到右 依次按照函数来操作, 从左向右进行聚合 (聚合:多个值变成一个值)
  def test1() : Unit ={
   // var result = List(1,2,3,4,5).reduceLeft(_-_) // 匿名函数, 左边数字 - 右边数字
   var result = List(1,2,3,4,5).reduceLeft((x,y)=>x-y)
    println(result)
  }

猜你喜欢

转载自chengjianxiaoxue.iteye.com/blog/2394337