Scala learning (functional programming, object-oriented programming)

functional programming

Basic functional programming

function definition

package learn03
object demo01 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //无参、无返回值
    def fun1(): Unit = {
    
    
      println("函数体")
    }
    fun1()

    //无参、有返回值
    def fun2(): String = {
    
    
      "xwk"
    }
    println(fun2())

    //有参、无返回值
    def fun3(name: String): Unit = {
    
    
      println(name)
    }
    fun3("xwk")

    //有参、有返回值
    def fun4(name: String): String = {
    
    
      "Hello " + name
    }
    println(fun4("xwk"))

    //多参、无返回值
    def fun5(hello: String, name: String): Unit = {
    
    
      println(hello + " " + name)
    }
    fun5("Hello", "xwk")

    //多参、有返回值
    def fun6(hello: String, name: String): String = {
    
    
      hello + " " + name
    }
    println(fun6("Hello", "xwk"))
  }
}

function parameters

package learn03
object demo02 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //可变参数
    def fun7(names: String*): Unit = {
    
    
      println(names)
    }
    fun7()
    fun7("xwk")
    fun7("xwk", "zxy")

    //可变参数不能放置在参数列表的前面,一般放置在参数列表的最后
    //def fun77(names:String*,name:String):Unit={},这是错误的写法
    def fun77(name: String, names: String*): Unit = {
    
    
      println(name)
      println(names)
    }

    //参数默认值
    def fun8(name: String, password: String = "000000"): Unit = {
    
    
      println(name + "," + password)
    }
    fun8("xwk", "123456")
    fun8("xwk")

    //带名参数
    def fun9(password: String = "000000", name: String): Unit = {
    
    
      println(name + "," + password)
    }
    fun9("123456", "xwk")
    fun9(name = "xwk")
  }
}

The principle of function to simplicity

package learn03
object demo03 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //省略return关键字
    def fun1(): String = {
    
    
      return "省略return关键字前"
    }
    def fun11(): String = {
    
    
      "省略return关键字"
    }
    println(fun1())
    println(fun11())

    //省略花括号
    def fun2(): String = "省略花括号"
    println(fun2())

    //省略返回值类型
    def fun3() = "省略返回值类型"
    println(fun3())

    //省略参数列表
    def fun4 = "省略参数列表"
    println(fun4) //正确
    //fun4()错误

    //省略等号
    //如果函数体中有明确的return语句,那么返回值类型不能省略
    def fun5_1(): String = {
    
    
      return "省略等号1"
    }
    println(fun5_1())

    //如果函数体返回值类型明确为Unit, 那么函数体中即使有return关键字也不起作用
    def fun5_2(): Unit = {
    
    
      return "省略等号2"
    }
    println(fun5_2())

    //如果函数体返回值类型声明为Unit, 但是又想省略,那么此时就必须连同等号一起省略
    def fun5_3(){
    
    
      return "省略等号3"
    }
    println(fun5_3())

    //省略名称和关键字
    () => {
    
    
      println("省略名称和关键字")
    }
  }
}

Higher-order functional programming

The so-called higher-order functions are actually using functions as a type, rather than as a specific grammatical structure.

package learn03

object demo04 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    //函数作为值
    def fun1(): String = {
    
    
      "xwk"
    }

    val a = fun1
    val b = fun1 _
    val c: () => Unit = fun1
    println(a)
    println(b)

    //函数作为参数
    def fun2(i: Int): Int = {
    
    
      i * 2
    }

    def fun22(f: Int => Int): Int = {
    
    
      f(10)
    }
    println(fun22(fun2))

    //函数作为返回值
    def fun3(i: Int): Int = {
    
    
      i * 2
    }

    def fun33() = {
    
    
      fun3 _
    }
    println(fun33()(10))

    //匿名函数
    def fun4(f: Int => Int): Int = {
    
    
      f(10)
    }

    println(fun4((x: Int) => {
    
    
      x * 20
    }))
    println(fun4((x) => {
    
    
      x * 20
    }))
    println(fun4((x) => x * 20))
    println(fun4(x => x * 20))
    println(fun4(_ * 20))

    //控制抽象
    def fun7(op: => Unit) = {
    
    
      op
    }

    fun7 {
    
    
      println("xx")
    }

    //闭包
    def fun5() = {
    
    
      val i = 20

      def fun55() = {
    
    
        i * 2
      }
      fun55 _
    }
    fun5()()

    //函数柯里化
    def fun6(i: Int)(j: Int) = {
    
    
      i * j
    }

    //递归函数
    def fun8(j: Int): Int = {
    
    
      if (j <= 1) {
    
    
        1
      } else {
    
    
        j * fun8(j - 1)
      }
    }
    println(fun8(5))

    //惰性函数
    def fun9(): String = {
    
    
      println("function......")
      "xwk"
    }
    lazy val x = fun9()
    println("........")
    println(x)
  }
}

Object-Oriented Programming

Basic Object Oriented Programming

Bag

The package keyword can be used in nested declarations

package learn03
package p1 {
    
    
  package p2 {
    
    
    package p3 {
    
    
      object demo01 {
    
    
        def main(args: Array[String]): Unit = {
    
    
          println("test...")
        }
      }
    }
  }
}

Sub-packages in the same source code file can directly access the content in the parent package without importing.
Packages in Scala can also be regarded as objects and declare properties and functions

import

The basic import syntax in scala
is exactly the same as in java. The syntax of import in java is relatively simple, and scala extends it.

package learn03
object demo05{
    
    
  def main(args: Array[String]): Unit = {
    
    
    //scala中的import语法可以在任意位置使用
    import java.util.ArrayList
    new ArrayList()
    //scala中可以导包,而不是岛类
    import java.util
    new util.ArrayList()
    //scala可以在同一行中导入相同包中的多个类,简化代码
    import java.util.{
    
    List,ArrayList}
    //屏蔽某个包中的类
    import java.util._
    import java.sql.{
    
    Date=>_,Array=>_,_}
    //给类起别名
    import java.util.{
    
    ArrayList=>AList}
    new AList()
    //可以使用类的绝对路径而不是相对路径
    import _root_.java.util.ArrayList
    //默认情况下,scala中会导入如下包和对象
    import java.lang._
    import scala._
    import scala.Predef._
  }
}

kind

class User{
    
    
      //类的主体内容
    }
    //对象 : new 类名(参数列表) 
    new User()

Multiple public classes can be declared in one source file in scala

Attributes

package learn03
object demo06 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    class User {
    
    
      var name : String = _ // 类属性其实就是类变量
      var age : Int = _ // 下划线表示类的属性默认初始化
    }
  }
}

access permission

private : 私有访问权限
private[包名]: 包访问权限
protected : 受保护权限,不能同包
            : 公共访问权限(默认)

method

The method of a class in Scala is actually a function, so the declaration method is exactly the same, but it must be called by using the object

package learn03
object demo07 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val user=new User
    user.login("xwk","000000")
  }
}
class User{
    
    
  def login(name:String,password:String):Boolean={
    
    
    false
  }
}

object

val | var 对象名 [:类型]  = new 类型()
var user : User = new User()

Construction method

package learn03
class User() {
    
     // 主构造函数
  var username : String = _
  def this( name:String ) {
    
     // 辅助构造函数,使用this关键字声明
    this() // 辅助构造函数应该直接或间接调用主构造函数
    username = name
  }
  def this( name:String, password:String ) {
    
    
    this(name) // 构造器调用其他另外的构造器,要求被调用构造器必须提前声明
  }
}

Advanced Object-Oriented Programming

inherit

package learn03
class Person {
    
    }
package learn03
class User extends Person{
    
    }

abstract

Scala calls an incomplete class an abstract class

abstract class Person{
    
    }

In Scala, if a method has only declaration but no implementation, it is an abstract method because it is incomplete.

abstract class Person{
    
    
  def test():Unit
}

In Scala, if a property has only a declaration and no initialization, it is an abstract property because it is incomplete.

abstract class Person{
    
    
  var name:String
}

If the subclass inherits the abstract class, it must implement the abstract method or complete the abstract property, otherwise it must also be declared as abstract, because it is still incomplete.

class User extends Person{
    
    
  var name:String="xwk"
}
abstract class Person{
    
    
  var name:String
}

singleton object

 The so-called singleton object means that only one object of a specified class can be created during the running of the program, but not multiple objects. Such objects can be obtained by special design methods, or by the language itself, such as object companion object
 Scala language is a completely object-oriented language, so there is no static operation (that is, there is no static concept in Scala). But in order to be able to interact with the Java language (because there is a static concept in Java), a special object is created to simulate a class object, which is a singleton object. If the name of the singleton object is consistent with the name of the class, it is called the companion object of the class of the singleton object. All "static" content of this class can be placed in its companion object and declared, and then directly called through the companion object name.
If If the class name is consistent with the name of the companion object, then this class is called a companion class. The Scala compiler can create companion class objects through the companion object's apply method. The apply method can be overloaded and passed parameters, and can be automatically recognized by the Scala compiler. So in use, it can actually be omitted.

class User {
    
     // 伴生类
}
object User {
    
     // 伴生对象
    def apply() = new User() // 构造伴生类对象
}
...
val user1 = new User()// 通过构造方法创建对象
Val user2 = User.apply() // 通过伴生对象的apply方法构造伴生类对象 
val user3 = User() // scala编译器省略apply方法,自动完成调用

おすすめ

転載: blog.csdn.net/weixin_46322367/article/details/125222984