【scala】1.基础

简介

一、安装scala地址:https://www.scala-lang.org/download/,经过sjava

二、在idea中编译运行。添加IDEA Scala(执行此操做后,pom文件中不用添加scala依赖,应为已经以lib库的方式加入)shell

进入Module Setting或者按F4进入界面,选择Gloabal Library,右键scala jar包,选择Add to Modules... 便可。express

一、Scala解释器

配置好环境变量后,shell输入scala。sass

一、基本操做语句session

scala> 3+4
res0: Int = 7

scala> 4*5+8
res1: Int = 28

二、Tab自动补全方法app

scala> "hello,scala"
res2: String = hello,scala

scala> res2.to
to        toBoolean   toByte        toDouble   toIndexedSeq   toIterable   toList   toLowerCase   toSeq   toShort    toString        toUpperCase
toArray   toBuffer    toCharArray   toFloat    toInt          toIterator   toLong   toMap         toSet   toStream   toTraversable   toVector

scala> res2.sort
sortBy   sortWith   sorted

scala> res2.sorted
res3: String = ,aacehlllos

三、REPL模式(read-eval-print-loop)dom

四、查看命令行,以冒号开头的都是命令操做ide

scala> :help
All commands can be abbreviated, e.g., :he instead of :help.
:completions <string>    output completions for the given string
:edit <id>|<line>        edit history
:help [command]          print this summary or command-specific help
:history [num]           show the history (optional num is commands to show)
:h? <string>             search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v]          show the implicits in scope
:javap <path|class>      disassemble a file or class name
:line <id>|<line>        place line(s) at the end of history
:load <path>             interpret lines in a file
:paste [-raw] [path]     enter paste mode or paste a file
:power                   enable power user mode
:quit                    exit the interpreter
:replay [options]        reset the repl and replay all previous commands
:require <path>          add a jar to the classpath
:reset [options]         reset the repl to its initial state, forgetting all session entries
:save <path>             save replayable session to a file
:sh <command line>       run a shell command (result is implicitly => List[String])
:settings <options>      update compiler options, if possible; see reset
:silent                  disable/enable automatic printing of results
:type [-v] <expr>        display the type of an expression without evaluating it
:kind [-v] <type>        display the kind of a type. see also :help kind
:warnings                show the suppressed warnings from the most recent line which had any

二、声明值和变量

一、val值不可变,var值可变。函数

scala> val answer = 1
answer: Int = 1

scala> var not = false
not: Boolean = false

二、必要的时候能够声明类型:变量:类型 = 值oop

scala> var greeting: String = null
greeting: String = null

scala> val s1,s2:String = "test"
s1: String = test
s2: String = test

三、经常使用类型

Byte Char Short Int Long Float Double

RichInt(Double、Char)

StringOps

四、算数和操做符重载

a 方法 b

a.方法(b)

不支持 ++ --

五、方法调用

若是没有参数,就不须要使用括号。

若是一个无参方法并不修改对象,调用时就能够不用写括号。

引入包的方式 _ 相似于java的*

能够直接使用半生对象的方法。

使用以scala开头的包时,能够省去scala的前缀。

六、apply方法

一、相似函数调用的语法:

s(i) <=> java中的s.charAt(i),C++中的s[i]

scala> val s = "abc"
s: String = abc

scala> s(2)
res9: Char = c

scala> s[2]
<console>:1: error: identifier expected but integer literal found.
       s[2]

背后的实现逻辑:apply

二、一样,以下的操做都是背后调用了操做对象所属类的apply方法

scala> BigInt("123456")
res10: scala.math.BigInt = 123456

scala> BigInt.apply("123456")
res12: scala.math.BigInt = 123456

scala> Array(1,2,3)
res13: Array[Int] = Array(1, 2, 3)

scala> Array.apply(1,2,3)
res14: Array[Int] = Array(1, 2, 3)

七、Scala Doc

相似于JavaDoc同样的文档查看系统。

L、练习

一、在scala中输入3.,会提示那些方法可使用?

scala> 3.
!=   +   <<   >=    abs         compareTo     getClass     isNaN           isValidChar    isWhole     round        to               toDegrees     toInt           toShort   underlying
%    -   <=   >>    byteValue   doubleValue   intValue     isNegInfinity   isValidInt     longValue   self         toBinaryString   toDouble      toLong          unary_+   until
&    /   ==   >>>   ceil        floatValue    isInfinite   isPosInfinity   isValidLong    max         shortValue   toByte           toFloat       toOctalString   unary_-   |
*    <   >    ^     compare     floor         isInfinity   isValidByte     isValidShort   min         signum       toChar           toHexString   toRadians       unary_~

二、在Scala REPL中,计算3的平方根,而后再对该值求平方。如今,这个结果与3相差多少?

scala> import scala.math._
import scala.math._

scala> sqrt(3)
res15: Double = 1.7320508075688772

scala> pow(res15,2)
res16: Double = 2.9999999999999996

scala> 3 - res16
res18: Double = 4.440892098500626E-16

三、res变量是val仍是var?

scala> res18 = res18 + 1
<console>:15: error: reassignment to val
       res18 = res18 + 1

显然是不可变的,即val。

四、Scala容许用数字乘以字符串,去REPL中试一下"crazy" * 3.这个操做作了什么?在ScalaDoc中如何找到这个操做?

scala> "crazy" * 3
res19: String = crazycrazycrazy

这个操做将字符串叠加了3次,造成一个新的字符串返回;在ScalaDoc中StringOps类中能够找到该方法

def *(n: Int): String
Return the current string concatenated n times.

五、 10 max 2的含义是什么?max定义在哪一个类中? 含义为返回10和2中值最大的那一个。也能够写为10.max(2)、2.max(10)

scala> 10 max 2
res0: Int = 10

定义在Int类中

def max(that: Int): Int
Returns this if this > that or that otherwise.

六、用BigInt计算2的1024次方。

scala> BigInt(2).pow(1024)
res8: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216

七、为了在使用probablePrime(100,Random)获取随机质数时不在probablePrime和Radom以前使用任何限定符,须要引入什么?

// Random引用
scala> import scala.util._
import scala.util._

// probablePrime引用
scala> import scala.math.BigInt._
import scala.math.BigInt._

scala> probablePrime(100,Random)
res8: scala.math.BigInt = 960697016320705319171295980203

八、建立随机文件的方式之一辈子成一个随机的BigInt,而后将他转换成36进制,返回相似于"qsnvbevtomcj38o06kul"这样的字符串。查阅scala文档找到实现该逻辑的方法。

scala> val num = BigInt.probablePrime(100,Random)
num: scala.math.BigInt = 661712999120439539288883430513

scala> num.toString(36)
res9: String = 1s5jrbb731snvh11spdd

九、在scala中如何获取字符串的首字符和尾字符。

scala> var s9 = "abcde"
s9: String = abcde

scala> s9(0)
res10: Char = a

scala> s9.last
res10: Char = e

十、take、drop、takeRight和dropRight这些字符串方法是作什么用的?和substring相比,他们的优势和缺点有什么呢?

1. 在StringLike中
* take:Selects first n elements.(选择开头的n个字符)
* takeRight :Selects last n elements.(选择末尾的n个字符)

2. StringOps
drop :Selects all elements except first n ones. (选择除了开头的n个字符)
dropRight:Selects all elements except last n ones. (选择除了末尾的n个字符)

substring: 选择子串,这个要构造一个新的字符串
相关文章
相关标签/搜索