文档章节

Scala basic from "Scala in Action"

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

© 著作权归作者所有

共有 人打赏支持
翟志军

翟志军

粉丝 337
博文 75
码字总数 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

在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 ⋅ 0

scala语言与java的区别

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

jhonephone ⋅ 2014/09/03 ⋅ 0

Akka实战:构建REST风格的微服务

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

羊八井 ⋅ 2015/11/27 ⋅ 0

Akka实战:分散、聚合模式

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

羊八井 ⋅ 2015/11/26 ⋅ 13

scala_2:函数(Function)

package cn.chinahadoop.scala /** * Created by jiangzl on 15/8/31. */ class Basic { } object Basic { def hello(name: String): String = { // return 可省略(默认返回最后一行) "hel......

片刻 ⋅ 2015/11/20 ⋅ 0

Play2 Action梳理

研究它的原因是在用它提供的,,的时候,感觉API提供的不够灵活。 play将后台处理前台的请求的过程封装为,我们先只看关于http部分的。也就是只看下。 Action 下面是 trait的一些信息 继承 ,也就...

lost_o0 ⋅ 2015/03/28 ⋅ 1

Scala下Play框架学习笔记(Actions,Controllers and Results)

Scala下Play框架的学习是一件辛苦的事情,因为该框架比较新,scala语言也较新,所以中文资料很少,经过同事推荐,去了如下英文网站看资料: https://www.playframework.com/documentation/2....

金明略 ⋅ 2016/12/22 ⋅ 0

Play之Scala-Web项目运行流程-简单分析(2)

为了方便开发,我们将此工程转化为Eclipse项目,然后通过sftp下载到本地并导入到Eclipse里分析! 如果您的项目还在运行,就关了(通过Ctr+C吧)它,然后进入play命令行下: [root@centos6-vb...

hanzhankang ⋅ 2014/03/07 ⋅ 0

Play 2.0 中文资料--翻译附注解(持续更新中)

最近在研究 PlayFramework 2.0,主要关注在使用 Scala 来写 Play 2.0 的应用,下面是从官方文档进行的翻译,并加入了大量的自己的理解与备注(Unmi 注: 起头的蓝色文字) Play 2.0 中文资料 - ...

YanbinQ ⋅ 2012/10/26 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

常见数据结构(二)-树(二叉树,红黑树,B树)

本文介绍数据结构中几种常见的树:二分查找树,2-3树,红黑树,B树 写在前面 本文所有图片均截图自coursera上普林斯顿的课程《Algorithms, Part I》中的Slides 相关命题的证明可参考《算法(第...

浮躁的码农 ⋅ 9分钟前 ⋅ 0

android -------- 混淆打包报错 (warning - InnerClass ...)

最近做Android混淆打包遇到一些问题,Android Sdutio 3.1 版本打包的 错误如下: Android studio warning - InnerClass annotations are missing corresponding EnclosingMember annotation......

切切歆语 ⋅ 25分钟前 ⋅ 0

eclipse酷炫大法之设置主题、皮肤

eclipse酷炫大法 目前两款不错的eclipse 1.系统设置 Window->Preferences->General->Appearance 2.Eclipse Marketplace下载【推荐】 Help->Eclipse Marketplace->搜索‘theme’进行安装 比如......

anlve ⋅ 33分钟前 ⋅ 0

vim编辑模式、vim命令模式、vim实践

vim编辑模式 编辑模式用来输入或修改文本内容,编辑模式除了Esc外其他键几乎都是输入 如何进入编辑模式 一般模式输入以下按键,均可进入编辑模式,左下角提示 insert(中文为插入) 字样 i ...

蛋黄Yolks ⋅ 38分钟前 ⋅ 0

大数据入门基础:SSH介绍

什么是ssh 简单说,SSH是一种网络协议,用于计算机之间的加密登录。 如果一个用户从本地计算机,使用SSH协议登录另一台远程计算机,我们就可以认为,这种登录是安全的,即使被中途截获,密码...

董黎明 ⋅ 57分钟前 ⋅ 0

web3j教程

web3j是一个轻量级、高度模块化、响应式、类型安全的Java和Android类库提供丰富API,用于处理以太坊智能合约及与以太坊网络上的客户端(节点)进行集成。 汇智网最新发布的web3j教程,详细讲解...

汇智网教程 ⋅ 今天 ⋅ 0

谷歌:安全问题机制并不如你想象中安全

腾讯科技讯 5月25日,如今的你或许已经对许多网站所使用的“安全问题机制”习以为常了,但你真的认为包括“你第一个宠物的名字是什么?”这些问题能够保障你的帐户安全吗? 根据谷歌(微博)安...

问题终结者 ⋅ 今天 ⋅ 0

聊聊spring cloud gateway的RedisRateLimiter

序 本文主要研究下spring cloud gateway的RedisRateLimiter GatewayRedisAutoConfiguration spring-cloud-gateway-core-2.0.0.RELEASE-sources.jar!/org/springframework/cloud/gateway/con......

go4it ⋅ 今天 ⋅ 0

169. Majority Element - LeetCode

Question 169. Majority Element Solution 思路:构造一个map存储每个数字出现的次数,然后遍历map返回出现次数大于数组一半的数字. 还有一种思路是:对这个数组排序,次数超过n/2的元素必然在中...

yysue ⋅ 今天 ⋅ 0

NFS

14.1 NFS介绍 NFS是Network File System的缩写 NFS最早由Sun公司开发,分2,3,4三个版本,2和3由Sun起草开发,4.0开始Netapp公司参与并主导开发,最新为4.1版本 NFS数据传输基于RPC协议,RPC...

派派菠菜 ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部