《快学scala》笔记及答案1

来源:互联网 发布:招聘淘宝美工兼客服 编辑:程序博客网 时间:2024/05/02 02:24

package com.zhuxiaoyu.chapter1
import scala.math._
/**
* 笔记
* 声明变量 (无需指定类型,在编译时自动匹配)
* val answer = 42 //不可改变的值,相当于java中final声明
* var answer = 42 //可改变的值
*
* val answer : String = “hello scala” //在必要时可以声明类型,所有的类型声明都在变量或函数的后面
*
*
* val value1,value2 = 100 //多个值一起声明
* val value1,value2 : String = null.
*
* 常用类型
* 12.toString //若方法没有参数,可以不需要方法名后的(),输出字符串”12”
* 1.to(10) //输出Range(1,2,3,4,5,6,7,8,9,10)
*
* 在Scala中没有像Java中的基本类型和包装类,Scala只有Int,Boolean,Char类,对应的具有许多操作函数类RichInt,RichChar等
* 在1.to(10)中,1被转换成了RichInt的对象,然后再对之处理,应用to方法
* 在”hello”.instersect(“world”)中,java.lang.String对象”hello”被隐式地转换成了一个StringOps的对象
*
* Scala的类型转换,没有强制类型转换,只有使用方法进行转换,如99.99.toInt 得到99.
*
* 操作符
* 对于Scala来说,所有的操作符其实现都是方法。
* 如a + b, 是方法a.+(b),在此+是方法名,scala对于特殊符号都是认为合法的字符串,如*##是合法的字符串,但是不建议这么命名
* 1 to 10 也是方法1.to(10)调用的结果
*
* scala没有++ 和–的操作符,因此要自增只能使用count += 1
* 不提供++操作符是因为Int类是不可变的,++只是合法的字符串,
*
* 函数调用过程,如Math包中的函数
* 1.导包 import scala.math._ //_字符是”通配符”,相当于Java中的*,///在方法中表示当前值
* 2.调用方法 sqrt(2),pow(2,5)
*
* scala没用静态的方法,但有类似的特性,叫单例对象
* 通常一个类对应有一个半生对象,其方法就像java的静态方法
*
* 标记为implicit的方法对应的是自动(隐式)转换。如,BIgInt对象拥有在需要时自动被调用的有int和long转换位BigInt的方法
*
*
*
* 声明Int[]数组时将在JVM中对应一个Java的int[]
*
*
* 在main函数中,参数Array[String] 中的String是Predef.String
* 若导入错误的package,将会导致不能运行,提示如下
* import com.sun.org.apache.xpath.internal.operations.String
* Chapter1 has a main method with parameter type Array[String],
* but com.zhuxiaoyu.chapter1.Chapter1 will not be a runnable program.
* Reason: main method must have exact signature (Array[String])Unit
*
*/

object Chapter1 {

def main(args: Array[String]) {
/**
* 1.
* scala> 3.
* != + <= >> getClass toDouble toString
* ## - >>> hashCode toFloat unary_+
* % / == ^ isInstanceOf toInt unary_-
* & < > asInstanceOf toByte toLong unary_~
* << >= equals toChar toShort |
*/
/**
* 2.
* scala> import scala.math._
* import scala.math._
*
* scala> sqrt(3)
* res1: Double = 1.7320508075688772
*
* scala> pow(res1,2)
* res2: Double = 2.9999999999999996
*/
/**
* 3. val
*
* 4. scala> “crazy” * 3
* res4: String = crazycrazycrazy
*
* 5.10.max(2) scala.math.max 比较10 和 2 输出大的值
*
* 6.BigInt(2).pow(1024)
* 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216
* 7.Random在scala.util.Random
* scala.math.BigInt._
*
* 8.scala.math.BigInt(scala.util.Random.nextInt).toString(36)
* 9.”Hello”(0)
* “hello”.take(1)
* “Hello”.reverse(0)
* “Hello”.takeRight
*
* 10.查询API即可 
* take是从字符串首开始获取字符串,
* drop是从字符串首开始去除字符串。 
* takeRight和dropRight是从字符串尾开始操作。 
* 这四个方法都是单方向的。
* 如果我想要字符串中间的子字符串,那么需要同时调用drop和dropRight,
* 或者使用substring 
*/
}
}

0 0
原创粉丝点击