文档章节

Scala basic from "Scala in Action"

翟志军
 翟志军
发布于 2015/02/23 17:25
字数 1020
阅读 57
收藏 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

© 著作权归作者所有

共有 人打赏支持
翟志军

翟志军

粉丝 343
博文 76
码字总数 79851
作品 2
深圳
程序员
Slick 3.0.0 RC1 发布,Scala 数据库访问层

Slick 是 TypeSafe 推出的 Scala 数据库访问库。开发者可以使用 Scala 语言风格来编写数据查询,而不是用 SQL,示例代码: object Coffees extends Table(String, Int, Double) { def name =...

oschina
2015/02/24
2.1K
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
163
0
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

没有更多内容

加载失败,请刷新页面

加载更多

Shell特殊符号总结以及cut,sort,wc,uniq,tee,tr,split命令

特殊符号总结一 * 任意个任意字符 ? 任意一个字符 # 注释字符 \ 脱义字符 | 管道符 # #号后的备注被忽略[root@centos01 ~]# ls a.txt # 备注 a.txt[root@centos01 ~]# a=1[root@centos01...

野雪球
28分钟前
1
0
OSChina 周二乱弹 —— 程序员圣衣

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @达尔文:分享Skeeter Davis的单曲《The End of the World》 《The End of the World》- Skeeter Davis 手机党少年们想听歌,请使劲儿戳(这里...

小小编辑
43分钟前
4
0
[ python import module ] 导入模块

import moudle_name ----> import module_name.py ---> import module_name.py文件路径 -----> sys.path (这里进行查找文件) # from app.web import Personimport app.web.Person as Pe......

_______-
昨天
3
0
Redis性能问题排查解决手册

一、性能相关的数据指标 通过Redis-cli命令行界面访问到Redis服务器,然后使用info命令获取所有与Redis服务相关的信息。通过这些信息来分析文章后面提到的一些性能指标。 nfo命令输出的数据可...

IT--小哥
昨天
1
0
mixin混入

①新建mixin.js文件 const mixin = { methods: { /** * 分页公共方法 */ handleSizeChange(val) { this.pageData.size = val; this.query(); }, hand......

不负好时光
昨天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部