当前位置:网站首页>Scala basic grammar learning-1

Scala basic grammar learning-1

2022-06-09 18:19:00 @Autowire

1 data type

 Insert picture description here
 Insert picture description here
 Insert picture description here

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

 Insert picture description here

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
}

 Insert picture description here
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 ;
 Insert picture description here

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()
 Insert picture description here

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")
    }
}

原网站

版权声明
本文为[@Autowire]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091809412693.html