文档章节

Scala basic from "Scala in Action"

翟志军
 翟志军
发布于 2015/02/23 17:25
字数 1020
阅读 58
收藏 0

basic type

    scala> val x: Int = 1
    x: Int = 1
    
    scala> val decimal = 11235
    decimal: Int = 11235
    
    scala> val decimal1 = 112345L
    decimal1: Long = 112345
    
    scala> val hexa = 0x23
    hexa: Int = 35
    
    scala> val octa = 023
    <console>:1: error: Decimal integer literals may not have a leading zero. (Octal  syntax is obsolete.)
           val octa = 023
                      ^
    scala> val d = 0.0
    d: Double = 0.0
    
    scala> val f = 0.0f
    f: Float = 0.0
    
    scala> d == f
    res0: Boolean = true
    
    scala> val exponent = 1e30
    exponent: Double = 1.0E30
    
    
    scala> val exponent = 1e30
    exponent: Double = 1.0E30
    
    scala> val capB = '\123'
    warning: there was one deprecation warning; re-run with -deprecation for details
    capB: Char = S
    
    scala> val \u0061\u006e\u0073  = 42
    ans: Int = 42
    
    scala> val ? = scala.math.Pi
    ?: Double = 3.141592653589793
    
    scala> ?
    res1: Double = 3.141592653589793
    
    scala> def ?(x:Double) = scala.math.sqrt(x)
    $qmark: (x: Double)Double
    
    scala> ?(1.3)
    res2: Double = 1.140175425099138
    
    scala> val bookname = "Scala in \" action\""
    bookname: String = Scala in " action"
    
    scala> val multiLine = """ This is a
         | multi line
         | String """
    multiLine: String =
    " This is a
    multi line
    String "
    
    scala> s"My Name $multiLine"
    res3: String =
    "My Name  This is a
    multi line
    String "
    
    scala> val book = <book>
         | <title>Scala in Action</title>
         | </book>
    book: scala.xml.Elem =
    <book>
    <title>Scala in Action</title>
    </book>
    
    
    scala> val message = "I didn't know xml could be so much fun"
    message: String = I didn't know xml could be so much fun
    
    scala> val code = "1"
    code: String = 1
    
    scala> val alert = <alert>
         | <message priority={code}>{message}</message>
         | <date>{new java.util.Date()}</date>
         | </alert>
    alert: scala.xml.Elem =
    <alert>
    <message priority="1">I didn't know xml could be so much fun</message>
    <date>Mon Feb 23 12:49:20 CST 2015</date>
    </alert>

declare

    scala> val constant = 87
    constant: Int = 87
    
    scala> constant = 98
    <console>:14: error: reassignment to val
           constant = 98
                    ^
    
    scala> var variable = 87
    variable: Int = 87
    
    scala>  variable = 89
    variable: Int = 89
    
    scala> var willKnowLater: String = _
    willKnowLater: String = null
    
    scala> var i: Int = _
    i: Int = 0
    
    scala> lazy val forLater = println("xx") // the lazy keyword is allowed only with val
    forLater: Unit = <lazy>
    
    scala> forLater
    xx
    
    scala> var a = 1
    a: Int = 1
    
    scala> lazy val b = a + 1
    b: Int = <lazy>
    
    scala> a = 5
    a: Int = 5
    
    scala> b
    res5: Int = 6
    
    // You can do that  using a pattern on the left side along with the variable declaration
    // The :: (called cons) is a method defined in List
    scala> val first :: rest = List(1, 2, 3)
    first: Int = 1
    rest: List[Int] = List(2, 3)
    
    scala> val first1 :: second :: third = List(1, 3, 5)
    first1: Int = 1
    second: Int = 3
    third: List[Int] = List(5)

function

在此输入图片描述

    scala> def myFirstMethod() = { "exciting times ahead" }
    myFirstMethod: ()String
    
    scala> myFirstMethod
    res6: String = exciting times ahead
    
    scala> def myFirstMethod =  "exciting times ahead"
    myFirstMethod: String
    
    scala> def max(a: Int, b: Int) = if(a > b) a else b
    max: (a: Int, b: Int)Int
    
    scala> max(5,4)
    res0: Int = 5
    
    
    scala> def toList[A](value: A) = List(value)
    toList: [A](value: A)List[A]
    
    scala> toList(1)
    res1: List[Int] = List(1)
    
    scala> toList("Scala rocks")
    res2: List[String] = List(Scala rocks)
    
    
    scala> val evenNumbers = List(2, 4, 6, 8, 10)
    evenNumbers: List[Int] = List(2, 4, 6, 8, 10)
    
    scala> evenNumbers.foldLeft(0) {(a: Int, b: Int) => a + b}
    res0: Int = 30
    
    scala> evenNumbers.foldLeft(0) {(a, b) => a + b}
    res1: Int = 30
    
    scala> evenNumbers.foldLeft(0) { _ + _ }
    res2: Int = 30
    
    
    val breakException = new RuntimeException("break exception")
    def breakable(op: => Unit) {
    try {
        op
    } catch { case _ => }
    }
    def break = throw breakException
    def install = {
        val env = System.getenv("SCALA_HOME")
        if(env == null) break
        println("found scala home lets do the real work")
    }

work with Array & List

    scala> val array = new Array[String](3)
    array: Array[String] = Array(null, null, null)
    
    scala> array(0) = "This"
    
    scala> array(1) = "is"
    
    scala> array(2) = "mutable"
    
    scala> array
    res3: Array[String] = Array(This, is, mutable)
    
    
    scala> array.foreach(println)
    This
    is
    mutable
    
    scala> val oldList = List(1,2)
    oldList: List[Int] = List(1, 2)
    scala> val newList = 3 :: oldList
    newList: List[Int] = List(3, 1, 2)
    scala> oldList
    res5: List[Int] = List(1, 2)
    
    scala> oldList :+ 3
    res6: List[Int] = List(1, 2, 3)
    
    
    scala> val myList = "This" :: "is" :: "immutable" :: Nil
    myList: List[String] = List(This, is, immutable)
    
    
    scala> newList.filterNot(_ == 3)
    res7: List[Int] = List(1, 2)

Controlling flow with loop and if

    scala> val aList = List(1,2,3)
    aList: List[Int] = List(1, 2, 3)
    
    scala> val bList = List(4,5,6)
    bList: List[Int] = List(4, 5, 6)
    
    
    scala> for{a <- aList; b <- bList} println(s"$a, $b")
    1, 4
    1, 5
    1, 6
    2, 4
    2, 5
    2, 6
    3, 4
    3, 5
    3, 6
    
    scala> for(a <- aList; b <- bList) println(s"$a, $b")
    1, 4
    1, 5
    1, 6
    2, 4
    2, 5
    2, 6
    3, 4
    3, 5
    3, 6
    
    scala> for(a <- aList) {
         | for(b <- bList) {
         |  println(s"$a, $b")
         | }
         | }
    1, 4
    1, 5
    1, 6
    2, 4
    2, 5
    2, 6
    3, 4
    3, 5
    3, 6
    
    
    scala> for{ a <- aList; b <- bList } yield a + b
    res2: List[Int] = List(5, 6, 7, 6, 7, 8, 7, 8, 9)
    
    scala> val xmlNode = <result>{res2.mkString(",")}</result>
    xmlNode: scala.xml.Elem = <result>5,6,7,6,7,8,7,8,9</result>

##Pattern matching

    scala> def printType(obj: AnyRef) = obj match {
         |  case s: String => println("String")
         |  case l: List[_] => println("List")
         |  case a: Array[_] => println("Array")
         |
         |  case d: java.util.Date => println("date")
         | }
    printType: (obj: AnyRef)Unit
    
    scala> printType("hello")
    String
    
    scala> printType(List(1,2))
    List
    
    scala> printType(new java.util.Date())
    date
    
    
    scala> List(1,2,3,4) match {
         |  case f :: s :: rest => List(f, s)
         |  case _ => Nil
         | }
    res7: List[Int] = List(1, 2)
    
    
    scala> def rangeMacher(num: Int) = num match {
         |   case within10 if within10 <= 10 => println("with in 0 to 10")
         |   case within100 if within100 <= 100 => println("with in 11 to 100")
    )    |   case beyond100 if beyond100 < Integer.MAX_VALUE => println("beyond 100"
         | }
    rangeMacher: (num: Int)Unit
    
    def rangeMatcher(num:Int) = num match {
     case within10 if within10 <= 10 => println("with in 0 to 10")
     case within100 if within100 <= 100 => println("with in 11 to 100")
     case _ => throw new IllegalArgumentException( "Only values between 0 and 100 are allowed") 
    }
    
    
    scala> try {
     rangeMatcher1(1000)
     } catch { case e: IllegalArgumentException => e.getMessage }
    res19: Any = Only values between 0 and 100 are allowed

© 著作权归作者所有

共有 人打赏支持
翟志军

翟志军

粉丝 347
博文 76
码字总数 79851
作品 2
深圳
程序员
私信 提问
在idea上建立一个sbt工程总是编译不过去,代码没有任何错误提示,求大神解答

Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=384M; support was removed in 8.0 [info] Loading global plugins from /home/aurora/.sbt/0.13/plugins [info] ......

AuroraTan
2017/06/19
212
0
Slick 3.0.0 RC1 发布,Scala 数据库访问层

Slick 是 TypeSafe 推出的 Scala 数据库访问库。开发者可以使用 Scala 语言风格来编写数据查询,而不是用 SQL,示例代码: Scala Slick 3.0.0 RC1 发布,源代码现已提供在:https://github....

oschina
2015/02/24
2.3K
2
scala语言与java的区别

scala支持关联映射,如可以用(key -> value)表示一个键值对 scala中的所有类型都是对象,包括基本数据类型 scala中的case语句用来判断接收的消息,比java中的switch...case...更专注 receiv...

jhonephone
2014/09/03
0
0
Akka实战:构建REST风格的微服务

使用Akka-Http构建REST风格的微服务,服务API应尽量遵循REST语义,数据使用JSON格式交互。在有错误发生时应返回:类似的JSON错误消息。 代码: https://github.com/yangbajing/akka-action ...

羊八井
2015/11/27
854
0
Akka实战:分散、聚合模式

分散与聚合:简单说就是一个任务需要拆分成多个小任务,每个小任务执行完后再把结果聚合在一起返回。 代码 http://git.oschina.net/yangbajing/akka-action 实例背景 本实例来自一个真实的线...

羊八井
2015/11/26
3.2K
13

没有更多内容

加载失败,请刷新页面

加载更多

Caffe(二)-Python-自定义网络

这里我们用一个例子先来体验一下 首先定义一下我们的环境变量 $PYTHONPATH,我这儿是Windows开发环境,至于Windows Caffe怎么编译由读者自己下去搞定 我使用的控制台是 Windows PowerShell 添...

Pulsar-V
32分钟前
2
0
ActiveMQ从入门到精通(二)之可靠性机制

ActiveMQ的可靠性机制 缘由( 确认JMS消息) 只要消息被确认之后,才认为消息被成功消费了。消息的成功消费包括三个阶段:客户端接收消息、客户端处理消息以及客户端确认消息。在事务性会话中...

一看就喷亏的小猿
39分钟前
0
0
源码分析 Mybatis 的 foreach 为什么会出现性能问题

背景 最近在做一个类似于综合报表之类的东西,需要查询所有的记录(数据库记录有限制),大概有1W条记录,该报表需要三个表的数据,也就是根据这 1W 个 ID 去执行查询三次数据库,其中,有一...

TSMYK
今天
7
0
IC-CAD Methodology企业实战之openlava

在云计算解决安全问题并成为IC界主流运算平台之前,私有的服务器集群系统仍然是各大IC公司的计算资源平台首选。 现在主流的服务器集群管理系统包括lsf,openlava,SkyForm,三者都属于lsf一系...

李艳青1987
今天
5
0
http response stream 字节流 接收与解码

在接收图片、音频、视频的时候,需要用到二进制流。 浏览器会发给客户端 字节Byte流,一串串的发过来_int8格式 -128~127(十进制),也就是8bit(位)。 客户端接收的时候,对接收到的字节收集,...

大灰狼wow
今天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部