学习笔记-01

Kotlin 学习笔记
原视频资料地址

你好世界

fun main(args: Array) {
    println("Hello, Kotlin!")
}

数据类型

数据类型

数据类型
fun main(args: Array) {
    val aByte:Byte=Byte.MAX_VALUE
    val bByte:Byte=Byte.MIN_VALUE
    println("MAX_VALUE is $aByte, MIN_VALUE is $bByte")
    
    val aInt:Int = 0b011 // 二进制
    println("aInt is $aInt")
}

输出

MAX_VALUE is 127, MIN_VALUE is -128
aInt is 3

初识函数

fun main(args: Array) {
    printOneStar()
    printThreeStars()
    printFiveStars()
    println("*******")
    printFiveStars()
    printThreeStars()
    printOneStar()
}

fun printOneStar() {
    println("   *   ")
}

fun printThreeStars() {
    println("  ***  ")
}

fun printFiveStars() {
    println(" ***** ")
}

输出

   *   
  ***  
 ***** 
*******
 ***** 
  ***  
   *  

Boolean

fun main(args: Array) {
    val num1 = Math.sqrt(5.0) - Math.sqrt(4.0)
    val num2 = Math.sqrt(4.0) - Math.sqrt(3.0)
    println(num1 > num2)
    
    val num3 = Math.pow(2.0, 100.0)
    val num4 = Math.pow(3.0, 75.0)
    println(num3 > num4)
}

输出

false
false

函数作业练习

fun sayHello(name: String) = "Hello $name"

fun checkAge(age: Int) = age > 18

fun saveLog(logLevel: Int) {}

fun main(args: Array) {
    println(sayHello("Leo"))
    println(checkAge(2))
    saveLog(1)
}

输出

Hello Leo
false

字符串

fun main(args: Array) {
    val template = """
        |今天
        |明天
        """.trimMargin("|")
    println(template)
    
    val template2 = "今天\n明天"
    println(template2)
}

输出

今天
明天
今天
明天
字符串比较
fun main(args: Array) {
    var str1 = "123"
    var str2 = "123"
    println(str1 == str2)
    println(str1.equals(str2))
    str1 = "ABC"
    str2 = "abc"
    println()
    println(str1 == str2)
    println(str1.equals(str2))
    println(str1.equals(str2, true)) // ignoreCase: true
}

输出

true
true

false
false
true

空值处理

fun main(args: Array) {
    println(heat("水"))
    println(heat(null))
}

fun heat(str: String?): String {
    return if (str == null) "不加热" else "加热$str"
}

输出

加热水
不加热

When表达式

fun gradeStudent(score: Int) = when(score) {
    10 -> println("Great")
    9 -> println("Nice")
    8 -> println("Better")
    7 -> println("Fine")
    6 -> println("Ok")
    else -> println("Bad")
}

fun main(args: Array) {
    gradeStudent(7)
}

输出

Fine

循环和范围

fun main(args: Array) {
    val nums = 1..100 // [1, 100]
    nums.map { it -> println(it) }
    val nums2 = 1 until 100 // [1, 100)
    nums2.map { it -> println(it) }
    val nums3 = 1..100 step 2
    nums3.map { println(it) }
    nums3.reversed().map { println(it) }
    println("total: ${nums3.count()}")
    val nums4 = 100 downTo 1
    nums4.map { println(it) }
}

List

fun main(args: Array) {
    val lists = listOf("a", "b", "c", "d")
    lists.map { println(it) }
    for ((i, e) in lists.withIndex()) {
        println("$i is $e")
    }
}

输出

a
b
c
d
0 is a
1 is b
2 is c
3 is d

Map

import java.util.*

fun main(args: Array) {
    val map = TreeMap()
    map["1"] = "good"
    map["2"] = "better"
    println(map["2"])
    val map2 = mapOf("1" to "good", "2" to "better")
    println(map2["1"])
}

输出

better
good

函数表达式

fun main(args: Array) {
    val i = { x: Int, y: Int -> x + y }
    println(i(3, 5))
    println(add(4, 5))
    val j: (Int, Int) -> Int = { x, y -> x + y }
    println(j(4, 5))
}

fun add(x: Int, y: Int) = x + y

输出

8
9
9

默认参数和具名参数

import kotlin.math.PI

fun getCirclePerimeter(pi: Double = PI,radius: Double) = 2 * pi * radius

fun getCirclePerimeter2(pi: Double = PI, diameter:Double) = pi * diameter

fun main(args: Array) {
    println(getCirclePerimeter(radius = 2.0))
    println(getCirclePerimeter2(diameter = 4.0))
}

输出

12.566370614359172
12.566370614359172

字符串和数字之间的转换

fun main(args: Array) {
    var a = "13"
    var b = 13
    a = b.toString()
    b = a.toInt()
    var c = "${a}3"
    b = c.toInt()
    println(b)
}

输出

133

人机交互-打字交互

fun main(args: Array) {
    println("First NUM:")
    val num1str = readLine()
    println("Second NUM:")
    val num2str = readLine()
    val num1 = num1str!!.toInt()
    val num2 = num2str!!.toInt()
    println("$num1 + $num2 = ${num1 + num2}")
}

输出

First NUM:
12
Second NUM:
13
12 + 13 = 25

异常处理

fun main(args: Array) {
    println("First NUM:")
    val num1str = readLine()
    println("Second NUM:")
    val num2str = readLine()
    try {
        val num1 = num1str!!.toInt()
        val num2 = num2str!!.toInt()
        println("$num1 + $num2 = ${num1 + num2}")
    } catch (e: NumberFormatException) {
        println("Wrong Number Type")
    }
}

输出

First NUM:
a
Second NUM:
b
Wrong Number Type

递归

fun main(args: Array) {
    println(fact(6))
}

fun fact(num: Int): Int = if (num == 1) 1 else num * fact(num - 1)

输出

720

BigInteger改写

import java.math.BigInteger

fun main(args: Array) {
    println(fact(BigInteger("100")))
}

fun fact(num: BigInteger): BigInteger = if (num == BigInteger.ONE) BigInteger.ONE else num * fact(num - BigInteger.ONE)

输出

93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

尾递归优化

fun main(args: Array) {
    println(tailrecAdd(100, 0))
}

tailrec fun tailrecAdd(num: Int, result: Int): Int = if (num == 0) result else tailrecAdd(num - 1, result + num)

输出

5050

初识面向对象

class Rect(val height: Int, val width: Int)

fun main(args: Array) {
    val rect = Rect(10, 20)
    println("Height is ${rect.height}")
    println("Width is ${rect.width}")
}

输出

Height is 10
Width is 20

静态属性和动态行为

class Girl(val character: String, val voice: String) {
    private fun smile() {
        println("Smile")
    }
    
    fun laugh() {
        smile()
        println("Ha Ha")
    }
}

fun main(args: Array) {
    val girl = Girl("Good", "Great")
    girl.laugh()
}

输出

Smile
Ha Ha

洗衣机实例

class WashMachine(val module: String, var size: Int) {
    private var isDoorOpen = false
    fun openDoor() {
        isDoorOpen = true
        println("Door is opened.")
    }
    
    fun closeDoor() {
        isDoorOpen = false
        println("Door is closed.")
    }
    
    fun start() {
        if (isDoorOpen) {
            println("Close the door first, please.")
        } else {
            println("Start working.")
        }
    }
}

fun main(args: Array) {
    var machine01 = WashMachine("小天鹅", 10)
    machine01.openDoor()
    machine01.start()
    machine01.closeDoor()
    machine01.start()
}

输出

Door is opened.
Close the door first, please.
Door is closed.
Start working.

封装

private关键字

继承

Father.kt

open class Father {
    var character: String = "内向"
    open fun action() {
        println("公共场合大声喧哗")
    }
}

Son.kt

class Son : Father() {
    override fun action() {
        println("公共场合很有礼貌")
    }
}

Test.kt

fun main(args: Array) {
    val son1 = Son()
    println("The character is ${son1.character}")
    son1.action()
}

输出

The character is 内向
公共场合很有礼貌

抽象类和继承

Human.kt

abstract class Human(var name: String) {
    abstract fun eat()
}

Man.kt

class Man(name: String) : Human(name) {
    override fun eat() {
        println("$name 大口吃")
    }
}

'Woman.kt`

class Woman(name: String) : Human(name) {
    override fun eat() {
        println("$name 小口吃")
    }
}

Test.kt

fun main(args: Array) {
    val man = Man("Maximus")
    val woman = Woman("Ivy")
    man.eat()
    woman.eat()
}

输出

Maximus 大口吃
Ivy 小口吃

抽象类和接口

  • 接口是事物的能力
  • 抽象类是事物的本质
    Human.kt
abstract class Human(var name: String) {
    abstract fun eat()
}

InterfaceMan.kt

interface InterfaceMan {
    fun action()
}

Test.kt

class PersonMan(name: String) : Human(name), InterfaceMan {
    override fun eat() {
        println("${name}大口吃饭")
    }
    
    override fun action() {
        println("${name}长胡子")
    }
    
}

fun main(args: Array) {
    val person = PersonMan("Maximus")
    person.eat()
    person.action()
}

输出

Maximus大口吃饭
Maximus长胡子

区别:抽象类是事物的本质,是一类事物都具备的东西;接口是事物的能力,只有一类中的一部分事物才具备这种能力。

委托和代理

by关键字
IWashBowl.kt

interface IWashBowl {
    fun washing()
}

BigHeadSon.kt

class BigHeadSon : IWashBowl {
    override fun washing() {
        println("我是大头儿子,我在开心得洗碗,一次一块钱")
    }
}

SmallHeadFather.kt

class SmallHeadFather : IWashBowl by BigHeadSon()

Test.kt

fun main(args: Array) {
    val fa = SmallHeadFather()
    fa.washing()
}

输出

我是大头儿子,我在开心得洗碗,一次一块钱

单例模式

IWashBowl.kt

interface IWashBowl {
    fun washing()
}

BigHeadSon.kt

object BigHeadSon : IWashBowl {
    override fun washing() {
        println("我是大头儿子,我在开心得洗碗,一次一块钱")
    }
}

SmallHeadFather.kt

class SmallHeadFather : IWashBowl by BigHeadSon { // 注意区别,没有括号
    override fun washing() {
        println("我是小头爸爸,我让我儿子洗碗")
        BigHeadSon.washing() // 区别,没有括号
    }
}

Test.kt

fun main(args: Array) {
    val fa = SmallHeadFather()
    fa.washing()
}

输出

我是小头爸爸,我让我儿子洗碗
我是大头儿子,我在开心得洗碗,一次一块钱

枚举类

enum class Week {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

fun main(args: Array) {
    println(Week.Monday)
    println(Week.Monday.ordinal)
    Week.values().filter { it.toString().startsWith("S") && it.toString().contains("n") }.map { println(it) }
    Week.values().asList().also(::println)
}

输出

Monday
1
Sunday
[Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]

密封类

作用:定义子类类型有限的类
密封类和枚举类的区别:密封类更在意类型;枚举类更在意数据

sealed class Animal {
    class Fish : Animal()
    class Dog : Animal()
    class Cat : Animal()
}

fun main(args: Array) {
    val type01 = Animal.Fish()
    val type02 = Animal.Dog()
    val type03 = Animal.Cat()
    sayHello(type01)
    sayHello(type02)
    sayHello(type03)
}

fun sayHello(animal: Animal) = when (animal) {
    is Animal.Fish -> println("Hello Fish")
    is Animal.Dog -> println("Hello Dog")
    is Animal.Cat -> println("Hello Cat")
}

输出

Hello Fish
Hello Dog
Hello Cat

你可能感兴趣的:(学习笔记-01)