当前位置:网站首页>Scala basic grammar learning-1
Scala basic grammar learning-1
2022-06-09 18:19:00 【@Autowire】
1 data type



Option:some && none
Map<k,v> map
map.put('a', 100)
map.get('b') No null pointer will be reported , Returns the none
map.get('a') return some(100)
object object, Equivalent to a singleton of a class , No need to use new Instantiation . The default definitions are static . So it can be written directly main Method . The constructor in the object will be executed the first time it is used , If an object has never been called , His constructor doesn't perform either .object Can't pass parameters ; If you have to pass parameters , Need to be used in apply Method .
object Lesson {
def apply(xname: String, xage: Int): Unit ={
print("xname : " + xname + ", " + "xage : " + xage)
}
}
object HelloApply {
def main(args: Array[String]): Unit = {
Lesson("zhaoshuai11", 26)
}
}
xname : zhaoshuai11, xage : 26
1.1 Declaration of variables and constants
When defining variables or constants , You can also write the return type , Generally omit , Such as :val a:Int = 10. Constants cannot be reassigned .
object Lesson {
def main(args: Array[String]): Unit = {
val a: Int = 100 // val a = 100
print(a)
}
}
100

object Lesson {
def main(args: Array[String]): Unit = {
var a: Int = 100
a = 200
print(a)
}
}
200
2 class
class Need to use new To instantiate . You can pass it on , The type must be specified for parameter passing ; With parameters, there is a constructor by default ; By default, the attributes in the class have getter、setter Method .
object Lesson {
def main(args: Array[String]): Unit = {
val person = new Person("zhaoshuai11", 25)
println(person.age)
println(person.name)
}
}
class Person(xname: String, xage: Int) {
val name = xname
val age = xage
}

The properties in the class can be used with private modification , Expressed as a private property ; In the same scala In file ,class Name and object When the names are the same , This class is called the companion class of the object , Objects are called companion objects of classes . They can access each other's private variables ;
object Lesson {
def main(args: Array[String]): Unit = {
val person = new Person("zhaoshuai11", 25)
person.sayName()
}
}
class Person(xname: String, xage: Int) {
val name = xname
val age = xage
def sayName(): Unit ={
print("hello, world " + name + ": " + age)
}
}
hello, world zhaoshuai11: 25
Rewrite construction this(), The first line in the construct must call the default construct this()
object Lesson {
def main(args: Array[String]): Unit = {
val person = new Person("zhaoshuai11", 25, 'F')
println(person.gender)
}
}
class Person(xname: String, xage: Int) {
val name = xname
val age = xage
var gender = 'M'
def this(yname: String, yage: Int, ygender: Char){
this(yname, yage)
gender = ygender
}
}
F
Class can write and execute code directly ( There is no need to encapsulate the method in the outer layer )(println). Class construction , Do not execute except for methods ( Except for the construction method ), Everything else is done .
object Lesson {
def main(args: Array[String]): Unit = {
val person = new Person("zhaoshuai11", 25, 'F')
println(person.gender)
}
}
class Person(xname: String, xage: Int) {
val name = xname
val age = xage
var gender = 'M'
println("*** before this(yname: String, yage: Int, ygender: Char) ***")
def this(yname: String, yage: Int, ygender: Char){
this(yname, yage)
gender = ygender
}
println("*** after this(yname: String, yage: Int, ygender: Char) ***")
}
*** before this(yname: String, yage: Int, ygender: Char) ***
*** after this(yname: String, yage: Int, ygender: Char) ***
F
Be careful :
1、 It is suggested that class names should be capitalized , Method initial is lowercase , Class and method nomenclature recommendations conform to hump nomenclature
3 if-else for while do-while
object Lesson {
def main(args: Array[String]): Unit = {
val i: Int= 10
if (i < 10) {
print("i < 10")
} else if (i == 10) {
print("i == 10")
} else {
print("i > 10")
}
}
}
object Lesson {
def main(args: Array[String]): Unit = {
for (i <- 1 to 9) {
for (j <- 1 to i) {
print(s"$i*$j=" + i * j + "\t")
if (i == j) {
println()
}
}
}
}
}
object Lesson {
def main(args: Array[String]): Unit = {
for (i <- 1 to 9 ; j <- 1 to i) {
print(s"$i*$j=" + i * j + "\t")
if (i == j) {
println()
}
}
}
}
object Lesson {
def main(args: Array[String]): Unit = {
val result = for (i <- 1 to 10 ; if (i % 2) == 0) yield i
println(result)
}
}
```e
```scala
while(){
},do {
}while()
4 Scala Method definition
1、 Method definition syntax use def To define
2、 You can define the parameters passed in , To specify the type of the passed in parameter
3、 Method can write the type of the return value or not , Automatically infer
4、scala When the method in has a return value , Can write return, Or not return, The last line in the method will be returned as the result . When writing return when , You must write the return value of the method .
object Lesson {
def main(args: Array[String]): Unit = {
def max(x: Int, y: Int): Int = {
if (x > y) {
return x
} else {
return y
}
}
val res = max(1, 2)
println(res)
}
}
5、 If the return value can be done on one line , Can be {} Omit not to write .
object Lesson {
def main(args: Array[String]): Unit = {
def max(x: Int, y: Int) = if (x > y) x else y
}
}
6、 If you remove the equal sign in front of the method body , Then the return type of this method must be Unit Of . hypothesis , The logic inside finally returns a string, Then the return value will be converted to Unit, And the value is discarded .
5 Methods and functions
5.1 Recursive method
Recursive methods should explicitly indicate the return type
object Lesson {
def main(args: Array[String]): Unit = {
def fun(i: Int): Int ={
if (i == 1) {
1
} else {
fun(i - 1) * i
}
}
println(fun(5))
}
}
5.2 Method of default value parameter
1、 In the function of default value , If the number of parameters passed in is the same as the function definition , The value passed in will override the default value .
2、 If you don't want to override the default values , The number of parameters passed in is less than the parameters of the defined function , You need to specify the parameter name .
object Lesson {
def main(args: Array[String]): Unit = {
def fun(a: Int = 10, b: String = "zhaoshuai11", c: Char = 'M'): Unit ={
println(a,b,c)
}
fun(11, "zhaoshuai12", 'F')
fun(b="zhaoshuai13")
}
}
(11,zhaoshuai12,F)
(10,zhaoshuai13,M)
5.3 Variable length parameter method
object Lesson {
def main(args: Array[String]): Unit = {
def fun(a: Int*): Int ={
var sum = 0
for (item <- a) {
sum += item
}
sum
}
val res = fun(1, 2, 3, 4, 5)
println(res)
}
}
5.4 Anonymous functions
1、 With ()=>{} The form that appears is called anonymous function , You don't need a function name
2、 As long as there is => , It's an anonymous function
3、 When the parameter used for the method is a function
object Lesson {
def main(args: Array[String]): Unit = {
def value1 = (a: Int) => {
print(a)
}
value1(1)
}
}
1
object Lesson {
def main(args: Array[String]): Unit = {
def value1 = (a: Int) => {
a
}
println(value1(1))
}
}
1
object Lesson {
def main(args: Array[String]): Unit = {
def value1 = () => {
1
}
val res = value1()
print(res)
}
}
1
5.5 Nested methods
object Lesson {
def main(args: Array[String]): Unit = {
def fun1() ={
def fun2(a: Int): Int ={
if (a == 1) {
1
} else {
a * fun2(a-1)
}
}
println(fun2(5))
}
fun1()
}
}
120
5.6 The argument to a function is a function
object Lesson {
def main(args: Array[String]): Unit = {
def fun(a: Int, b: Int): Int ={
a + b
}
def fun1(f: (Int, Int)=>Int, s: String): String = {
val i = f(100, 100)
i + ", " + s
}
val res = fun1(fun, "hello")
print(res)
}
}
200, hello
object Lesson {
def main(args: Array[String]): Unit = {
def fun1(f: (Int, Int)=>Int, s: String): String = {
val i = f(100, 100)
i + ", " + s
}
println(fun1((a, b) => {
a * b
}, "hello"))
}
}
5.7 The return is a function
Explicitly declare that the return type is a function
object Lesson {
def main(args: Array[String]): Unit = {
def fun(a: String): (String, String) => String = {
def fun1(b: String, c: String): String = {
a + ", " + b + c
}
fun1
}
println(fun("hello")("world", "!"))
}
}
Do not explicitly declare the return type
object Lesson {
def main(args: Array[String]): Unit = {
def fun(a: String) = {
def fun1(b: String, c: String): String = {
a + ", " + b + c
}
// Underline to indicate Turn a method into a function
fun1 _
}
println(fun("hello")("world", "!"))
}
}
5.8 The underlined method indicates that the method can be forcibly converted to a function
object Lesson {
def main(args: Array[String]): Unit = {
def add(a: Int = 10, b: Int = 20) = {
a + b
}
val function1: (Int, Int) => Int = add _
}
}
5.9 Coriolis function - For implicit conversion, use
def func(a:Int,b:Int)(c:Int,d:Int) = {
a+b+c+d
}
func(1,2)(3,4)
6 Strings and collections
6.1 character string
object Lesson {
def main(args: Array[String]): Unit = {
var a: String = "hello"
var b: String = "HELLO"
print(a.equals(b))
print(a.equalsIgnoreCase(b))
// false true
println(a.indexOf('e')) // 1
}
}
6.2 Array
object Lesson {
def main(args: Array[String]): Unit = {
var array = Array[String]("a", "b", "c", "d")
for (elem <- array) {
print(elem)
}
array.foreach(print)
var array1 = new Array[Int](3)
array1(0) = 100
array1(1) = 100
array1(2) = 100
}
}
object Lesson {
def main(args: Array[String]): Unit = {
var array = new Array[Array[String]](3)
array(0) = Array[String]("a", "c", "c")
array(1) = Array[String]("a", "c", "c")
array(2) = Array[String]("a", "c", "c")
array.foreach(item => {
item.foreach(println)
})
for (elem <- array) {
for (elem <- elem) {
println(elem)
}
}
}
}
object Lesson {
def main(args: Array[String]): Unit = {
val res = Array.fill(5)("hello")
res.foreach(println)
}
}
hellohellohellohellohello
object Lesson {
def main(args: Array[String]): Unit = {
val array = ArrayBuffer[String]("a", "b", "c")
array.+=:("head")
array.append("e","f")
array.+=("tail")
array.foreach(println)
}
}
head
a
b
c
e
f
tail
6.3 List
object Lesson {
def main(args: Array[String]): Unit = {
val list = List[String]("a", "b", "c")
list.foreach(print)
for (elem <- list) {
print(elem)
}
}
}
object Lesson {
def main(args: Array[String]): Unit = {
val list = List[Int](1,2,3,4,5,6,7,8,9,10)
val res = list.filter(item => {
item % 2 == 0
})
res.foreach(println)
}
}
object Lesson {
def main(args: Array[String]): Unit = {
var list = List[String]("zhao shuai", "zhao fei", "zhao meng");
val res = list.flatMap(item => {
item.split(" ")
})
res.foreach(println)
}
}
zhao
shuai
zhao
fei
zhao
meng
object Lesson {
def main(args: Array[String]): Unit = {
var list = List[String]("zhao shuai", "zhao fei", "zhao meng");
val res = list.map(item => {
item.split(" ")
})
res.foreach(println)
}
}
[Ljava.lang.String;@48140564
[Ljava.lang.String;@58ceff1
[Ljava.lang.String;@7c30a502
object Lesson {
def main(args: Array[String]): Unit = {
val listBuffer = ListBuffer[Int](1, 2, 3, 4, 5, 6, 7)
listBuffer.append(8, 9, 10)
listBuffer.+=(11)
listBuffer.+=:(-1)
listBuffer.foreach(item => {
println(item)
})
}
}
-1
1
2
3
4
5
6
7
8
9
10
11
6.4 Set
set The assembly will automatically de weight
set Traverse foreach,for
intersection :intersect ,&
Difference set : diff ,&~
A subset of :subsetOf
Maximum :max
Minimum :min
Turn it into an array : toList
Convert to string :mkString(“~”)
object Lesson {
def main(args: Array[String]): Unit = {
val set = Set[Int](1, 2, 3, 4, 4, 5, 6, 1) // 5 1 6 2 3 4
val set1 = Set[Int](1, 2, 9, 10)
val res1 = set.intersect(set1) // 1 2 set & set1
val res = set.diff(set1) // 5 6 3 4 set &~ set1
}
}
import scala.collection.mutable.Set
object Lesson {
def main(args: Array[String]): Unit = {
val set = Set[Int](1, 2, 3, 3)
set.+=(4)
set.foreach(print) // 1 2 3 4
}
}
6.5 Map
object Lesson {
def main(args: Array[String]): Unit = {
val map: Map[String, Int] = Map[String, Int]("a" -> 1, "b" -> 2, "c" -> 3) //Map(a -> 1, b -> 2, c -> 3)
val map1 = Map[String, Int](("a", 100), ("b", 200), ("c", 300)) //Map(a -> 100, b -> 200, c -> 300)
// map.foreach(print) // (a,1)(b,2)(c,3)
for (elem <- map) {
val key: String = elem._1
val value: Int = elem._2
println(s"$key, $value")
}
// a, 1
// b, 2
// c, 3
}
}
object Lesson {
def main(args: Array[String]): Unit = {
val map: Map[String, Int] = Map[String, Int]("a" -> 1, "b" -> 2, "c" -> 3) //Map(a -> 1, b -> 2, c -> 3)
val resOption: Option[Int] = map.get("a")
val resValue: Int = resOption.get
print(resOption) // Some(1)
print(resValue) // 1
val resOption2: Option[Int] = map.get("d")
val resValue2: Int = resOption2.get // Exception in thread "main" java.util.NoSuchElementException: None.get
print(resOption2)
print(resValue2)
val resOption3: Option[Int] = map.get("d")
val resValue3: Int = resOption3.getOrElse(100)
println(resOption3) // None
println(resValue3) // 100
}
}
Merge map
++ example :map1.++(map2) --map1 Add map2
++: example :map1.++:(map2) –map2 Add map1
Be careful : Merge map Will map The same in key Of value Replace
// Merge map
val map1 = Map(
(1,"a"),
(2,"b"),
(3,"c")
)
val map2 = Map(
(1,"aa"),
(2,"bb"),
(2,90),
(4,22),
(4,"dd")
)
map1.++:(map2).foreach(println)
map1.++(map2).foreach(println)
filter: Filter , Leave a qualified record
count: Count the number of qualified records
contains:map Does it contain a key
exist: Does the qualified record exist
import scala.collection.mutable.Map
6.6 Tuple
Tuple definition : Same as list , Unlike lists, tuples can contain different types of elements . The values of tuples are constructed by including individual values in parentheses .
Create tuples and values :
val tuple = new Tuple(1) have access to new
val tuple2 = Tuple(1,2) May not be used new, It can also be written directly as val tuple3 =(1,2,3)
Take the value with ”._XX” You can get the value in the tuple
Be careful :tuple Most support 22 Parameters
object Lesson {
def main(args: Array[String]): Unit = {
// establish , Most support 22 individual
val tuple1: Tuple1[Int] = new Tuple1[Int](1)
val tuple2: (String, Int) = Tuple2("zs", 100)
val tuple22 = new Tuple22(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)
println(s"${
tuple2._1}, ${
tuple2._2}") // zs, 100
// println(s"${tuple2._1, tuple2._2}") // The wrong way to write
val t = Tuple2((1, 2), ("zhangsan", "lisi"))
println(t._1._2)
}
}
// Traversal tuples
val iterator: Iterator[Any] = tuple4.productIterator
iterator.foreach(println)
// Flip of binary tuples
println(tuple2)
println(tuple2.swap)
7 Trait
Scala Trait( features ) amount to Java The interface of , It's actually more powerful than an interface . Unlike the interface , It also defines the implementation of properties and methods . In general Scala Class of can inherit more than one Trait, The result is multiple inheritance .Trait( features ) It's defined in a way similar to a class , But the keywords it uses are trait.
Trait Can't pass on the reference . Inherit the first Trait use extends keyword , We will inherit others later Trait use with keyword .
trait Speak {
def speak(name: String): Unit = {
println(s"$name is speaking...")
}
}
trait Listen {
def listen(name: String): Unit = {
println(s"$name is listening...")
}
}
class Person(name: String) extends Speak with Listen {
val pname = name
}
object Lesson {
def main(args: Array[String]): Unit = {
val person = new Person("zs")
person.speak(person.pname)
person.listen(person.pname)
}
}
zs is speaking...
zs is listening...
trait IsEql {
def isEql(o: Any): Boolean
def isNotEql(o: Any): Boolean = {
!isEql(o)
}
}
class Point(xx: Int, yy: Int) extends IsEql {
val x = xx
val y = yy
override def isEql(o: Any): Boolean = {
o.isInstanceOf[Point] && o.asInstanceOf[Point].x == this.x
}
}
object Lesson {
def main(args: Array[String]): Unit = {
val point1 = new Point(1, 2);
val point2 = new Point(1, 3)
println(point1.isEql(point2))
}
}
true
8 Pattern matching match
case _ amount to default, Everything can be matched , Put it at the end
match You can match values and types
There will be value conversion in the matching process
Match from top to bottom , Automatically terminate after matching
Pattern matching external { } It can be omitted
object MatchTest {
def main(args: Array[String]): Unit = {
val tuple = (1, 2, 1.2, true, 'c', "abc")
val ite = tuple.productIterator
// ite.foreach(i=>{
// matchTest(i)
// })
ite.foreach(matchTest)
}
def matchTest(o:Any)={
o match {
case 1 => println("value is 1")
case i:Int => println(s"type is Int,value is $i")
case d:Double =>println(s"type is Double,value is $d")
case 'c' =>println("value is Char")
case _ => println("no match ...")
}
}
}
9 Sample class
Use keywords case Modified class , It is called the sample class
This class implements by default getter、setter、toString、equals、 copy、hashCode Other methods
Sample classes can new Or not new
case class Animals(name:String,age:Int)
object CaseClass {
def main(args: Array[String]): Unit = {
val a1 = Animals("miao", 2)
println(a1)
println(a1.hashCode())
}
}
10 Implicit values and implicit parameters
Add before parameter implicit, Will automatically be in the same scope ( The same class or object ) Find implicit parameters of the same type in
The implicit value of a parameter of the same type can only appear in the scope once
If the method has only one parameter and is an implicit parameter , It can be used directly implicit Define this parameter , When calling, you can directly create a type without passing in parameters
If there are some parameters in the method that need implicit conversion , Then the method needs to be defined in the way of coriolism , And the implicit parameter must be placed in the second bracket
object ImplicitTest {
def printName(implicit name:String): Unit ={
println(s"the name is $name")
}
// Some parameters require implicit conversion
def printNameAndAge(age:Int)(implicit name:String)={
println(s"the name is $name,the age is $age")
}
def main(args: Array[String]): Unit = {
implicit val name1 = "zhangsan"
printName
printName("lisi")
printNameAndAge(15)
printNameAndAge(15)("lisi")
}
}
边栏推荐
- 电脑小知识与优化
- Golang基础(4)
- Development and practice of the martyr's family search system
- ElasticSerach
- 【工作随笔记】Tina 系统的 ADB、声卡、网卡、串口多路共存
- Twitter plans to provide musk with access to relevant databases as early as this week
- mysql版本驱动问题
- 11年程序员给本科、研究生应届生以及准备从事后台开发同学的建议,学习进阶之路
- Golang Foundation (2)
- 155_模型_Power BI & Power Pivot 进销存之安全库存
猜你喜欢

redis源码学习-05_字典、哈希表

Redis source code learning-01_ Debugging redis source code in clion

NLP- 关键词提取 - 综述

JsonPath-教程

redis源码学习-03_动态字符串SDS

Development and practice of the martyr's family search system

AI chief architect 3-aica-ai application practice in smart city

Win10安装WSL1在D、E、F盘

How to learn the process of KD tree construction and search with cases?

进程控制--->进程终止
随机推荐
Management of free memory
混合云存储发展方向
Golang基础(3)
如何实现自定义富文本编辑器标签
DM8 5 methods to view SQL execution plan (for test + tuning)
ZigBee组网从未如此简单!
Golang Foundation (3)
Redis knowledge points & summary of interview questions
什么是波场TRX 钱包开发
转:彼得·德鲁克:什么样的老师才是真正的老师?
crontab定时执行任务
Acitivit的心路历程:Activiti6.0自定义任意跳转命令【包含回退】
ElasticSerach
Bienvenue à la plateforme d'écriture InfoQ!
Pytorch set random seed
[notes of advanced mathematics] Green formula, Gauss formula, Stokes formula, field theory
155_ Model_ Safety stock of power Bi & power pivot purchase, sales and inventory
EasyNVR非按需拉流返回的RTMP流地址无法播放如何处理?
shell记录
华为云原生之数据仓库服务GaussDB(DWS)的深度使用与应用实践【这次高斯不是数学家】