├── _config.yml
├── img
├── ic_qq.png
└── ic_kotlin.png
├── .gitattributes
├── .idea
└── dictionaries
│ └── loser_s_computer.xml
├── src
└── main
│ └── java
│ └── com
│ └── kotlin
│ └── leran
│ ├── basis
│ ├── HelloWorld.kt
│ ├── Constant.kt
│ ├── NoteDemo.kt
│ ├── VariableAndConstantDemo.kt
│ ├── NullAndNullCheckDemo.kt
│ ├── OperatorStringDemo.kt
│ ├── OperatorDemo.kt
│ ├── ControlStatementDemo.kt
│ └── DataTypeDemo.kt
│ ├── function
│ ├── ExpandFunDemo.kt
│ ├── InlineFunDemo.kt
│ ├── InfixFunDemo.kt
│ ├── lambda
│ │ └── LambdaDemo.kt
│ ├── BasisFunctionDemo.kt
│ └── SeniorFunctionDemo.kt
│ ├── design
│ ├── factory
│ │ ├── method
│ │ │ ├── demo2
│ │ │ │ ├── IChinaFactory.kt
│ │ │ │ ├── AmericaFactory.kt
│ │ │ │ ├── HuaweiFactory.kt
│ │ │ │ ├── XiaoMiFactory.kt
│ │ │ │ ├── IPhoneFactory.kt
│ │ │ │ ├── IPhone.kt
│ │ │ │ ├── HuaweiPhone.kt
│ │ │ │ ├── XiaoMiPhone.kt
│ │ │ │ ├── IChinaPhone.kt
│ │ │ │ └── ApplePhone.kt
│ │ │ └── demo1
│ │ │ │ ├── IFactory.kt
│ │ │ │ ├── IProduce.kt
│ │ │ │ ├── FactoryA.kt
│ │ │ │ ├── FactoryB.kt
│ │ │ │ ├── ProduceA.kt
│ │ │ │ └── ProduceB.kt
│ │ ├── simple
│ │ │ ├── demo2
│ │ │ │ ├── ProduceFactory.kt
│ │ │ │ └── Produce.kt
│ │ │ ├── demo3
│ │ │ │ └── ConcreteProduce.kt
│ │ │ └── demo1
│ │ │ │ ├── IFruit.kt
│ │ │ │ ├── Banana.kt
│ │ │ │ ├── FirstFruitFactory.kt
│ │ │ │ ├── Apple.kt
│ │ │ │ ├── Grape.kt
│ │ │ │ ├── SecondFruitFactory.kt
│ │ │ │ └── ThirdFruitFactory.kt
│ │ └── TestFactory.kt
│ ├── observer
│ │ ├── demo1
│ │ │ ├── Observer.kt
│ │ │ ├── ConcreteObserver.kt
│ │ │ ├── Subject.kt
│ │ │ └── ConcreteSubject.kt
│ │ └── TestObserver.kt
│ ├── adapter
│ │ ├── obj
│ │ │ ├── ObjAdaptee.kt
│ │ │ ├── ObjTarget.kt
│ │ │ └── ObjAdapter.kt
│ │ ├── cls
│ │ │ ├── ClsAdaptee.kt
│ │ │ ├── ClsTarget.kt
│ │ │ └── ClsAdapter.kt
│ │ ├── default
│ │ │ ├── MyAnimListener.kt
│ │ │ ├── Listener.kt
│ │ │ └── AnimListener.kt
│ │ └── TestAdapter.kt
│ ├── proxy
│ │ ├── statics
│ │ │ ├── demo1
│ │ │ │ ├── IStaticMoney.kt
│ │ │ │ ├── Driver.kt
│ │ │ │ ├── MoneyProxy.kt
│ │ │ │ └── FirstDriver.kt
│ │ │ └── demo2
│ │ │ │ ├── IStaticTicket.kt
│ │ │ │ ├── User.kt
│ │ │ │ ├── RailwayProxy.kt
│ │ │ │ └── PlaneProxy.kt
│ │ ├── dynamic
│ │ │ ├── jdk
│ │ │ │ ├── IDynamicTicket.kt
│ │ │ │ ├── Boat.kt
│ │ │ │ ├── Plane.kt
│ │ │ │ ├── Railway.kt
│ │ │ │ └── ProxyHandler.kt
│ │ │ └── cglib
│ │ │ │ ├── Car.kt
│ │ │ │ └── TestCglibFactory.kt
│ │ └── TestProxy.kt
│ ├── singleton
│ │ ├── KotlinInstance.kt
│ │ ├── SeventhInstance.kt
│ │ ├── SecondInstance.kt
│ │ ├── SixthInstance.kt
│ │ ├── FourthInstance.kt
│ │ ├── FifthInstance.kt
│ │ ├── ThirdInstance.kt
│ │ └── FirstInstance.kt
│ └── policy
│ │ ├── demo
│ │ ├── CarTicket.kt
│ │ ├── PlaneTicket.kt
│ │ ├── GaoTieTicket.kt
│ │ └── IBuyTicket.kt
│ │ └── TestPolicy.kt
│ ├── coroutines
│ ├── CancelCoroutineDemo.kt
│ └── Basis.kt
│ ├── cls
│ ├── classDemo
│ │ ├── SealedClassDemo.kt
│ │ ├── DataClassDemo.kt
│ │ ├── ClassDemo1.kt
│ │ ├── AbstractClassDemo.kt
│ │ ├── FieldDemo.kt
│ │ ├── EnumDemo.kt
│ │ ├── InheritClsDemo.kt
│ │ ├── InnerClassDemo.kt
│ │ └── InterfaceDemo.kt
│ └── TypealiasDemo.kt
│ ├── TestApplication.kt
│ └── other
│ ├── CollectionDemo.kt
│ └── OperaCollectionDemo.kt
├── .gitignore
├── pom.xml
├── KotlinLearn.iml
└── README.md
/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-slate
--------------------------------------------------------------------------------
/img/ic_qq.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jetictors/KotlinLearn/HEAD/img/ic_qq.png
--------------------------------------------------------------------------------
/img/ic_kotlin.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jetictors/KotlinLearn/HEAD/img/ic_kotlin.png
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto
2 | *.css linguist-vendored
3 | *.scss linguist-vendored
4 | *.js linguist-vendored
5 | *.xml linguist-vendored
--------------------------------------------------------------------------------
/.idea/dictionaries/loser_s_computer.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/HelloWorld.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin环境搭建 运行Hello World
5 | * author : Jetictors
6 | * time : 2017/8/31 23:20
7 | * version : 1.0.1
8 | */
9 | class HelloWorld{
10 |
11 | fun test(){
12 | println("Hello World !")
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/ExpandFunDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function
2 |
3 | /**
4 | * Desc : 拓展函数实例
5 | * Author : Jetictors
6 | * Time : 2019/9/17 17:13
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | class ExpandFunDemo{
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.ear
17 | *.zip
18 | *.tar.gz
19 | *.rar
20 |
21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
22 | hs_err_pid*
23 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/IChinaFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 抽象工厂角色(中国手机工厂)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:01
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IChinaFactory : IPhoneFactory
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/InlineFunDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function
2 |
3 |
4 | /**
5 | * Desc : 内联函数实例
6 | * Author : Jetictors
7 | * Time : 2019/9/17 14:52
8 | * Email : zhengxcfutures@gmail.com
9 | * Version : v-1.0.1
10 | */
11 |
12 |
13 |
14 | class InlineFunDemo{
15 |
16 |
17 |
18 | }
19 |
20 | fun main(){
21 | }
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/observer/demo1/Observer.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.observer.demo1
2 |
3 | /**
4 | * Desc : 抽象观察者
5 | * Author : Jetictors
6 | * Time : 2019-12-16 15:35
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface Observer{
11 |
12 | /**
13 | * 更新
14 | */
15 | fun response()
16 |
17 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/obj/ObjAdaptee.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.obj
2 |
3 | /**
4 | * Desc : 对象适配器 源角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:53
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | class ObjAdaptee{
11 |
12 | fun operatorFirst() : String{
13 | return "object first method"
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/cls/ClsAdaptee.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.cls
2 |
3 | /**
4 | * Desc : 类适配器 源角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:53
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | open class ClsAdaptee{
11 |
12 | open fun operatorFirst() : String{
13 | return "class first method"
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/IFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 抽象工厂角色
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IFactory{
11 |
12 | /**
13 | * 创建产品对象
14 | */
15 | fun createProduce() : IProduce
16 |
17 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/IProduce.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 抽象产品角色
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IProduce{
11 |
12 | /**
13 | * 具体产品的公有逻辑
14 | */
15 | fun showTest(name : String)
16 |
17 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/FactoryA.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 具体工厂角色A
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FactoryA : IFactory{
11 |
12 | override fun createProduce() : IProduce{
13 | return ProduceA()
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/FactoryB.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 具体工厂角色B
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FactoryB : IFactory{
11 |
12 | override fun createProduce() : IProduce{
13 | return ProduceB()
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/observer/demo1/ConcreteObserver.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.observer.demo1
2 |
3 | /**
4 | * Desc : 具体观察者
5 | * Author : Jetictors
6 | * Time : 2019-12-16 15:47
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ConcreteObserver(val name : String) : Observer{
11 |
12 | override fun response() {
13 | println("$name 收到了通知")
14 | }
15 |
16 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo2/ProduceFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo2
2 |
3 | /**
4 | * Desc : 省略了抽象角色的工厂类
5 | * Author : Jetictors
6 | * Time : 2019-12-17 17:31
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | class ProduceFactory{
12 |
13 | fun createProduce() : Produce {
14 | return Produce("first produce")
15 | }
16 |
17 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo1/IStaticMoney.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo1
2 |
3 | /**
4 | * Desc : 静态代理2
5 | * Author : Jetictors
6 | * Time : 2019-12-12 17:32
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IStaticMoney {
11 |
12 | /**
13 | * 收钱
14 | * [count] 人数
15 | * [price] 单价
16 | */
17 | fun giveMoney(count : Int, price : Int)
18 |
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/jdk/IDynamicTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.jdk
2 |
3 | /**
4 | * Desc : 动态代理接口
5 | * Author : Jetictors
6 | * Time : 2019-12-12 15:42
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IDynamicTicket {
11 |
12 | /**
13 | * 买票过程
14 | * [travel] 行程
15 | * [price] 价格
16 | */
17 | fun buyTicket(travel : String, price : Double)
18 |
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/KotlinInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : kotlin提供的单列模式(即 饿汉式单列)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:07
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | object KotlinInstance{
12 |
13 | /**
14 | * 测试函数
15 | */
16 | fun testInstance(){
17 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo2/IStaticTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo2
2 |
3 | /**
4 | * Desc : 静态代理接口
5 | * Author : Jetictors
6 | * Time : 2019-12-12 15:42
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IStaticTicket {
11 |
12 | /**
13 | * 买票过程
14 | * [travel] 行程
15 | * [price] 价格
16 | */
17 | fun buyTicket(travel : String, price : Double)
18 |
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/AmericaFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体工厂角色(美国手机工厂)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:01
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class AmericaFactory : IPhoneFactory{
11 |
12 | override fun createPhone(type : String, time : String): IPhone {
13 | return ApplePhone(type, time)
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/HuaweiFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体工厂角色(华为手机工厂)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:01
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class HuaweiFactory : IChinaFactory{
11 |
12 | override fun createPhone(type : String, time : String): IPhone {
13 | return HuaweiPhone(type, time)
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/XiaoMiFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体工厂角色(小米手机工厂)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:01
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class XiaoMiFactory : IChinaFactory{
11 |
12 | override fun createPhone(type : String, time : String): IPhone {
13 | return XiaoMiPhone(type, time)
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/SeventhInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式七(静态内部类)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | enum class SeventhInstance{
11 |
12 | INSTANCE;
13 |
14 | /**
15 | * 测试函数
16 | */
17 | fun testInstance(){
18 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/cls/ClsTarget.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.cls
2 |
3 | /**
4 | * Desc : 类适配器 目标角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:51
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | *
10 | */
11 | interface ClsTarget{
12 |
13 | /**
14 | * 操作1
15 | */
16 | fun operatorFirst() : String
17 |
18 | /**
19 | * 操作2
20 | */
21 | fun operatorSecond() : String
22 |
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/IPhoneFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 抽象工厂
5 | * Author : Jetictors
6 | * Time : 2019-12-18 11:57
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IPhoneFactory{
11 |
12 | /**
13 | * 生产手机
14 | * [type] 手机型号
15 | * [time] 生产日期
16 | */
17 | fun createPhone(type : String, time : String) : IPhone
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/default/MyAnimListener.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.default
2 |
3 | /**
4 | * Desc :
5 | * Author : Jetictors
6 | * Time : 2019-12-30 12:11
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | class MyAnimListener : AnimListener(){
11 |
12 | override fun onStart() {
13 | println("my anim is start")
14 | }
15 |
16 | override fun onEnd() {
17 | println("my anim is end")
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/obj/ObjTarget.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.obj
2 |
3 | /**
4 | * Desc : 对象适配器 目标角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:51
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | *
10 | */
11 | interface ObjTarget{
12 |
13 | /**
14 | * 操作1
15 | */
16 | fun operatorFirst() : String
17 |
18 | /**
19 | * 操作2
20 | */
21 | fun operatorSecond() : String
22 |
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/ProduceA.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 具体产品角色A
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ProduceA : IProduce{
11 |
12 | /**
13 | * 具体产品的公有逻辑
14 | */
15 | override fun showTest(name : String){
16 | println("create produce A is success ! name = $name")
17 | }
18 |
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/cglib/Car.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.cglib
2 |
3 | /**
4 | * Desc : cglib动态代理
5 | * Author : Jetictors
6 | * Time : 2019-12-13 15:46
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | open class Car{
11 |
12 | fun buyCarTicket(travel : String, price : Double){
13 | println("我买汽车票, 行程为: ${travel}, 价格是:${price}元")
14 | println("买票中")
15 | println("...")
16 | }
17 |
18 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/jdk/Boat.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.jdk
2 |
3 | /**
4 | * Desc : 买船票
5 | * Author : Jetictors
6 | * Time : 2019-12-13 11:24
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Boat : IDynamicTicket{
11 |
12 | override fun buyTicket(travel: String, price: Double) {
13 | println("我买船票, 行程为: ${travel}, 价格是:${price}元")
14 | println("买票中")
15 | println("...")
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/jdk/Plane.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.jdk
2 |
3 | /**
4 | * Desc : 买机票
5 | * Author : Jetictors
6 | * Time : 2019-12-13 11:24
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Plane : IDynamicTicket{
11 |
12 | override fun buyTicket(travel: String, price: Double) {
13 | println("我买机票, 行程为: ${travel}, 价格是:${price}元")
14 | println("买票中")
15 | println("...")
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/jdk/Railway.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.jdk
2 |
3 | /**
4 | * Desc : 买火车票
5 | * Author : Jetictors
6 | * Time : 2019-12-13 11:24
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Railway : IDynamicTicket{
11 |
12 | override fun buyTicket(travel: String, price: Double) {
13 | println("我买火车票, 行程为: ${travel}, 价格是:${price}元")
14 | println("买票中")
15 | println("...")
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo2/Produce.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo2
2 |
3 | /**
4 | * Desc : 具体产品(当只有一个具体产品是,抽象角色可省略)
5 | * Author : Jetictors
6 | * Time : 2019-12-17 17:28
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | data class Produce(var name : String){
11 |
12 | fun update(){
13 | println("更新产品 $name")
14 | }
15 |
16 | }
17 |
18 | interface IApple{
19 |
20 |
21 |
22 | }
23 |
24 | class OneApple : IApple {
25 |
26 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo3/ConcreteProduce.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo3
2 |
3 | /**
4 | * Desc : 把抽象角色、具体角色、工厂类合并再一起,
5 | * Author : Jetictors
6 | * Time : 2019-12-17 17:31
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | class ConcreteProduce{
12 |
13 | companion object{
14 | fun createProduce() : ConcreteProduce {
15 | return ConcreteProduce()
16 | }
17 | }
18 |
19 | fun show(){}
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/IPhone.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 抽象角色
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IPhone{
11 |
12 | /**
13 | * 阐述自己
14 | */
15 | fun aboutSelf()
16 |
17 | /**
18 | * 生产日期
19 | */
20 | fun createTime()
21 |
22 | /**
23 | * 生产地
24 | */
25 | fun createAddress()
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo1/Driver.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo1
2 |
3 | /**
4 | * Desc : 委托对象
5 | * Author : Jetictors
6 | * Time : 2019-12-12 18:18
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.0
9 | */
10 |
11 | open class Driver : IStaticMoney{
12 |
13 | override fun giveMoney(count : Int, price : Int) {
14 | println("这趟车坐了${count}个人, 每个人${price}元钱")
15 | val result = count * price
16 | println("收费成功,共收得车费${result}元")
17 | }
18 |
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo2/User.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo2
2 |
3 | /**
4 | * Desc : 委托类A
5 | * Author : Jetictors
6 | * Time : 2019-12-12 16:04
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | open class User : IStaticTicket {
11 |
12 | /**
13 | * 具体的业务逻辑
14 | */
15 | override fun buyTicket(travel : String, price : Double) {
16 | println("买票中")
17 | println("行程为:${travel}, 价格为:${price}元")
18 | println("...")
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/cls/ClsAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.cls
2 |
3 | /**
4 | * Desc : 类适配器 适配器角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:53
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | class ClsAdapter : ClsAdaptee(), ClsTarget{
11 |
12 | override fun operatorSecond(): String {
13 | return "class second method"
14 | }
15 |
16 | override fun operatorFirst(): String {
17 | return super.operatorFirst().plus("adapter success !")
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/observer/demo1/Subject.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.observer.demo1
2 |
3 | /**
4 | * Desc : 抽象主题(被观察者)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 15:32
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface Subject{
11 |
12 | /**
13 | * 添加观察者
14 | */
15 | fun attach(observer: Observer)
16 |
17 | /**
18 | * 移除观察者
19 | */
20 | fun detach(observer: Observer)
21 |
22 | /**
23 | * 通知观察者
24 | */
25 | fun notifyObserver()
26 |
27 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/HuaweiPhone.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体产品角色(华为手机)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:17
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class HuaweiPhone(override val type: String, override val time: String) : IChinaPhone{
11 |
12 | override fun aboutSelf() {
13 | println("I`m Huawei Phone $type")
14 | }
15 |
16 | override fun createTime() {
17 | println(time)
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/XiaoMiPhone.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体产品角色(小米手机)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:17
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class XiaoMiPhone(override val type: String, override val time: String) : IChinaPhone{
11 |
12 | override fun aboutSelf() {
13 | println("I`m XiaoMi Phone $type")
14 | }
15 |
16 | override fun createTime() {
17 | println(type)
18 | }
19 |
20 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/obj/ObjAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.obj
2 |
3 | /**
4 | * Desc : 对象适配器 适配器角色
5 | * Author : Jetictors
6 | * Time : 2019-12-30 11:53
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | class ObjAdapter(private var adaptee: ObjAdaptee) : ObjTarget{
11 |
12 | override fun operatorFirst(): String {
13 | return adaptee.operatorFirst().plus("adapter success!")
14 | }
15 |
16 | override fun operatorSecond(): String {
17 | return "object second method"
18 | }
19 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/policy/demo/CarTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.policy.demo
2 |
3 | /**
4 | * Desc : 汽车票策略
5 | * Author : Jetictors
6 | * Time : 2019-12-16 11:42
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class CarTicket : IBuyTicket{
11 |
12 | override fun getTicketMoney(travel : String, price : Double): Double {
13 | println("行程为 : $travel \n 票价为 : $price")
14 | return price
15 | }
16 |
17 | override fun getType(): Int {
18 | return IBuyTicket.TYPE_CAR
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo1/ProduceB.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo1
2 |
3 | /**
4 | * Desc : 具体产品角色B
5 | * Author : Jetictors
6 | * Time : 2019-12-18 15:00
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ProduceB : IProduce{
11 |
12 | /**
13 | * 具体产品的公有逻辑
14 | */
15 | override fun showTest(name : String){
16 | println("create produce B is success ! name = $name")
17 | }
18 |
19 | /**
20 | * 具体产品的特有逻辑
21 | */
22 | fun testB(){}
23 |
24 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/IChinaPhone.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 抽象产品角色(中国手机)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:37
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IChinaPhone : IPhone{
11 |
12 | /**
13 | * 类型
14 | */
15 | val type : String
16 |
17 | /**
18 | * 生产时间
19 | */
20 | val time : String
21 |
22 | override fun createAddress() {
23 | println("Made in China")
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/IFruit.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | /**
4 | * Desc : 抽象角色
5 | * Author : Jetictors
6 | * Time : 2019-12-17 16:23
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | interface IFruit{
12 |
13 | /**
14 | * 生长
15 | */
16 | fun grow()
17 |
18 | /**
19 | * 种植
20 | */
21 | fun plant()
22 |
23 | /**
24 | * 收获
25 | */
26 | fun harvest()
27 |
28 | /**
29 | * 价格
30 | */
31 | var price : Double
32 |
33 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/policy/demo/PlaneTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.policy.demo
2 |
3 | /**
4 | * Desc : 飞机票策略
5 | * Author : Jetictors
6 | * Time : 2019-12-16 11:42
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class PlaneTicket : IBuyTicket{
11 |
12 | override fun getTicketMoney(travel : String, price : Double): Double {
13 | println("行程为 : $travel \n 票价为 : ${price * 5}")
14 | return price * 5
15 | }
16 |
17 | override fun getType(): Int {
18 | return IBuyTicket.TYPE_PLANE
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/policy/demo/GaoTieTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.policy.demo
2 |
3 | /**
4 | * Desc : 汽车票策略
5 | * Author : Jetictors
6 | * Time : 2019-12-16 11:42
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class GaoTieTicket : IBuyTicket{
11 |
12 | override fun getTicketMoney(travel : String, price : Double): Double {
13 | println("行程为 : $travel \n 票价为 : ${price * 2.5}")
14 | return price * 2.5
15 | }
16 |
17 | override fun getType(): Int {
18 | return IBuyTicket.TYPE_GAO_TIE
19 | }
20 |
21 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/SecondInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式二(饿汉模式)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class SecondInstance private constructor(){
11 |
12 | companion object{
13 | // 直接初始化
14 | val sInstance: SecondInstance = SecondInstance()
15 | }
16 |
17 | /**
18 | * 测试函数
19 | */
20 | fun testInstance(){
21 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
22 | }
23 |
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/default/Listener.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.default
2 |
3 | /**
4 | * Desc :
5 | * Author : Jetictors
6 | * Time : 2019-12-30 12:10
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | interface Listener{
11 |
12 | /**
13 | * 开始
14 | */
15 | fun onStart()
16 |
17 | /**
18 | * 正在运行
19 | */
20 | fun onResume()
21 |
22 | /**
23 | * 暂停
24 | */
25 | fun onPause()
26 |
27 | /**
28 | * 结束
29 | */
30 | fun onEnd()
31 |
32 | /**
33 | * 重复
34 | */
35 | fun onRepeat()
36 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/method/demo2/ApplePhone.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.method.demo2
2 |
3 | /**
4 | * Desc : 具体产品角色(苹果手机)
5 | * Author : Jetictors
6 | * Time : 2019-12-27 15:17
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ApplePhone(val type : String, val time : String) : IPhone{
11 |
12 | override fun aboutSelf() {
13 | println("I`m Apple Phone $type")
14 | }
15 |
16 | override fun createTime() {
17 | println(time)
18 | }
19 |
20 | override fun createAddress() {
21 | println("made in America")
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/Banana.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | /**
4 | * Desc : 具体角色
5 | * Author : Jetictors
6 | * Time : 2019-12-17 16:28
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Banana(override var price: Double) : IFruit {
11 |
12 | override fun grow() {
13 | println("grow banana...")
14 | }
15 |
16 | override fun plant() {
17 | println("plant banana...")
18 | }
19 |
20 | override fun harvest() {
21 | println("harvest banana ...")
22 | println("I`m banana, price : $price")
23 | }
24 |
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/FirstFruitFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | /**
4 | * Desc : 普通工厂模式
5 | * Author : Jetictors
6 | * Time : 2019-12-17 16:41
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FirstFruitFactory{
11 |
12 | /**
13 | * 根据类型创建
14 | */
15 | fun createFactory(type : String) : IFruit?{
16 | return when(type){
17 | "apple" -> Apple("red", 12.8)
18 | "banana" -> Banana(8.8)
19 | "grape" -> Grape(false, 15.98)
20 | else -> null
21 | }
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/SixthInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式六(静态内部类)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class SixthInstance private constructor(){
11 |
12 | companion object{
13 | fun getInstance() = Holder.sInstance
14 | }
15 |
16 | private object Holder{
17 | val sInstance = SixthInstance()
18 | }
19 |
20 | /**
21 | * 测试函数
22 | */
23 | fun testInstance(){
24 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo1/MoneyProxy.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo1
2 |
3 | /**
4 | * Desc : 代理对象
5 | * Author : Jetictors
6 | * Time : 2019-12-12 18:13
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class MoneyProxy(private val proxy : IStaticMoney) : IStaticMoney{
11 |
12 | override fun giveMoney(count : Int, price : Int) {
13 | doBefore()
14 | proxy.giveMoney(count, price)
15 | doAfter()
16 | }
17 |
18 | private fun doBefore(){
19 | println("开门上车,向司机拿表")
20 | }
21 |
22 | private fun doAfter(){
23 | println("填单,关门走人")
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/Apple.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | /**
4 | * Desc : 具体角色
5 | * Author : Jetictors
6 | * Time : 2019-12-17 16:28
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Apple(private val color : String, override var price: Double) : IFruit {
11 |
12 | override fun grow() {
13 | println("grow apple...")
14 | }
15 |
16 | override fun plant() {
17 | println("plant apple...")
18 | }
19 |
20 | override fun harvest() {
21 | println("harvest apple ...")
22 | println("I`m apple, color : $color \t price : $price")
23 | }
24 |
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/Grape.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | /**
4 | * Desc : 具体角色
5 | * Author : Jetictors
6 | * Time : 2019-12-17 16:28
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class Grape(private val seed : Boolean, override var price: Double) : IFruit {
11 |
12 | override fun grow() {
13 | println("grow grape...")
14 | }
15 |
16 | override fun plant() {
17 | println("plant grape...")
18 | }
19 |
20 | override fun harvest() {
21 | println("harvest grape ...")
22 | println("I`m grape, seed : $seed \t price : $price")
23 | }
24 |
25 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/Constant.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : 常量的使用
5 | * author : Jetictors
6 | * time : 2018/5/4 23:37
7 | * version : v1.0.1
8 | */
9 |
10 | // 1. 顶层声明
11 | const val NUM_A : String = "顶层声明"
12 |
13 | class Constant {
14 |
15 | // 2. 在object修饰的类中
16 | object TestConst{
17 | const val NUM_B = "object修饰的类中"
18 | }
19 |
20 | // 3. 伴生对象对象中
21 | class TestClass{
22 | companion object {
23 | const val NUM_C = "伴生对象中声明"
24 | }
25 | }
26 |
27 | fun test(){
28 | println("numA = $NUM_A")
29 | println("numB = ${TestConst.NUM_B}")
30 | println("numC = ${TestClass.NUM_C}")
31 | }
32 |
33 | }
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/default/AnimListener.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter.default
2 |
3 | /**
4 | * Desc :
5 | * Author : Jetictors
6 | * Time : 2019-12-30 12:11
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-
9 | */
10 | open class AnimListener : Listener{
11 | override fun onStart() {
12 | println("anim start")
13 | }
14 |
15 | override fun onResume() {
16 | println("anim resume")
17 | }
18 |
19 | override fun onPause() {
20 | println("anim pause")
21 | }
22 |
23 | override fun onEnd() {
24 | println("anim end")
25 | }
26 |
27 | override fun onRepeat() {
28 | println("anim repeat")
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/FourthInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式四(懒汉模式 + 双重锁)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FourthInstance private constructor(){
11 |
12 | companion object{
13 |
14 | private var sInstance : FourthInstance? = null
15 |
16 | fun getInstance() = sInstance ?: synchronized(this){
17 | sInstance ?: FourthInstance().also { sInstance = it }
18 | }
19 |
20 | }
21 |
22 | /**
23 | * 测试函数
24 | */
25 | fun testInstance(){
26 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
27 | }
28 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/observer/demo1/ConcreteSubject.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.observer.demo1
2 |
3 | /**
4 | * Desc : 具体主题(被观察者)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 15:39
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ConcreteSubject : Subject{
11 |
12 | private val mObserverList = mutableListOf()
13 |
14 | override fun attach(observer: Observer) {
15 | mObserverList.add(observer)
16 | }
17 |
18 | override fun detach(observer: Observer) {
19 | mObserverList.remove(observer)
20 | }
21 |
22 | override fun notifyObserver() {
23 | for (observer in mObserverList) {
24 | observer.response()
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo1/FirstDriver.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo1
2 |
3 | /**
4 | * Desc : 委托对象1
5 | * Author : Jetictors
6 | * Time : 2019-12-12 18:18
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.0
9 | */
10 |
11 | class FirstDriver : Driver(){
12 |
13 | override fun giveMoney(count : Int, price : Int) {
14 | doBefore()
15 |
16 | println("这趟车坐了${count}个人, 每个人${price}元钱")
17 | val result = count * price
18 | println("收费成功,共收得车费${result}元")
19 |
20 | doAfter()
21 | }
22 |
23 | private fun doBefore(){
24 | println("开门上车,向司机拿表")
25 | }
26 |
27 | private fun doAfter(){
28 | println("填单,关门走人")
29 | }
30 |
31 | }
32 |
33 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo2/RailwayProxy.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo2
2 |
3 | /**
4 | * Desc : 代理类A(买火车票)
5 | * Author : Jetictors
6 | * Time : 2019-12-12 16:02
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class RailwayProxy(private val proxy : IStaticTicket) : IStaticTicket {
11 |
12 | override fun buyTicket(travel : String, price : Double) {
13 | doBefore()
14 | proxy.buyTicket(travel, price)
15 | doAfter()
16 | }
17 |
18 | private fun doBefore(){
19 | println("去火车票代售点")
20 | println("...")
21 | }
22 |
23 | private fun doAfter(){
24 | println("确认班次、座位等信息")
25 | println("付款")
26 | println("...")
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/FifthInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式五(懒汉式 + 双重锁 + volatile)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FifthInstance private constructor(val name: String){
11 |
12 | companion object{
13 |
14 | @Volatile private var sInstance : FifthInstance? = null
15 |
16 | fun getInstance(name : String) = sInstance ?: synchronized(this){
17 | sInstance ?: FifthInstance(name).also { sInstance = it }
18 | }
19 |
20 | }
21 |
22 | /**
23 | * 测试函数
24 | */
25 | fun testInstance(){
26 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/statics/demo2/PlaneProxy.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.statics.demo2
2 |
3 | /**
4 | * Desc : 代理类B(买飞机票)
5 | * Author : Jetictors
6 | * Time : 2019-12-12 16:02
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class PlaneProxy(private val proxy : IStaticTicket) : IStaticTicket {
11 |
12 | override fun buyTicket(travel : String, price : Double) {
13 | doBefore()
14 | proxy.buyTicket(travel, price)
15 | doAfter()
16 | }
17 |
18 | private fun doBefore(){
19 | println("去机票代售点")
20 | println("开始身份验证")
21 | println("...")
22 | }
23 |
24 | private fun doAfter(){
25 | println("确认班次、座位等信息")
26 | println("付款")
27 | println("...")
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/ThirdInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式三(懒汉模式-同步))
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class ThirdInstance private constructor(){
11 |
12 | companion object{
13 | private var sInstance : ThirdInstance? = null
14 |
15 | @Synchronized
16 | fun getInstance() : ThirdInstance?{
17 | if (null == sInstance){
18 | sInstance = ThirdInstance()
19 | }
20 | return sInstance
21 | }
22 | }
23 |
24 | /**
25 | * 测试函数
26 | */
27 | fun testInstance(){
28 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
29 | }
30 |
31 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/policy/demo/IBuyTicket.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.policy.demo
2 |
3 | /**
4 | * Desc : 策略模式接口
5 | * Author : Jetictors
6 | * Time : 2019-12-16 11:27
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | interface IBuyTicket{
11 |
12 | companion object{
13 |
14 | // 汽车票
15 | const val TYPE_CAR = 0
16 |
17 | // 高铁票
18 | const val TYPE_GAO_TIE = 1
19 |
20 | // 动车票
21 | const val TYPE_DONG_CHE = 2
22 |
23 | // 火车票
24 | const val TYPE_RAILWAY = 3
25 |
26 | // 飞机票
27 | const val TYPE_PLANE = 4
28 |
29 | // 船票
30 | const val TYPE_BOAT = 5
31 |
32 | }
33 |
34 | /**
35 | * 获取票价
36 | * [travel] 行程
37 | */
38 | fun getTicketMoney(travel : String, price : Double) : Double
39 |
40 | /**
41 | * 获取车票类型
42 | */
43 | fun getType() : Int
44 | }
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | KotlinLearn
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 1.3.50
13 |
14 |
15 |
16 |
17 | org.jetbrains.kotlinx
18 | kotlinx-coroutines-core
19 | 1.3.1
20 |
21 |
22 |
23 | cglib
24 | cglib
25 | 2.2.2
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/coroutines/CancelCoroutineDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.coroutines
2 |
3 | import kotlinx.coroutines.*
4 |
5 | /**
6 | * Desc : 协程取消测试
7 | * Author : Jetictors
8 | * Time : 2019/10/11 11:08
9 | * Email : zhengxcfutures@gmail.com
10 | * Version : v-1.0.1
11 | */
12 | class CancelCoroutineDemo{
13 |
14 | fun test(){
15 | first()
16 | }
17 |
18 | private fun first() = runBlocking {
19 | val job = launch {
20 | repeat(50){
21 | println("job: I'm sleeping $it ...")
22 | delay(500)
23 | }
24 | }
25 |
26 | delay(1300)
27 | println("job: I'm wait")
28 | // job.cancel()
29 | // job.join()
30 | job.cancelAndJoin()
31 | println("job: I'm quit")
32 | }
33 |
34 | private fun second() = runBlocking {
35 |
36 | }
37 |
38 | private fun third() = runBlocking {
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/SecondFruitFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | import com.kotlin.leran.design.factory.simple.demo1.Apple
4 | import com.kotlin.leran.design.factory.simple.demo1.Banana
5 | import com.kotlin.leran.design.factory.simple.demo1.Grape
6 | import com.kotlin.leran.design.factory.simple.demo1.IFruit
7 |
8 | /**
9 | * Desc : 多个工厂方法模式
10 | * Author : Jetictors
11 | * Time : 2019-12-17 16:41
12 | * Email : zhengxcfutures@gmail.com
13 | * Version : v-1.0.1
14 | */
15 | class SecondFruitFactory{
16 |
17 | /**
18 | * 创建苹果
19 | */
20 | fun createApple() : IFruit {
21 | return Apple("green", 8.8)
22 | }
23 |
24 | /**
25 | * 创建香蕉
26 | */
27 | fun createBanana() : IFruit {
28 | return Banana(5.5)
29 | }
30 |
31 | /**
32 | * 创建葡萄
33 | */
34 | fun createGrape() : IFruit {
35 | return Grape(true, 12.8)
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/policy/TestPolicy.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.policy
2 |
3 | import com.kotlin.leran.design.policy.demo.CarTicket
4 | import com.kotlin.leran.design.policy.demo.GaoTieTicket
5 | import com.kotlin.leran.design.policy.demo.IBuyTicket
6 | import com.kotlin.leran.design.policy.demo.PlaneTicket
7 |
8 | /**
9 | * Desc : 测试策略模式
10 | * Author : Jetictors
11 | * Time : 2019-12-30 11:36
12 | * Email : zhengxcfutures@gmail.com
13 | * Version : v-1.0.1
14 | */
15 | class TestPolicy{
16 |
17 | fun test(type : Int){
18 | testPolicyDemo(type)
19 | }
20 |
21 | /**
22 | * 测试策略类
23 | */
24 | private fun testPolicyDemo(type : Int){
25 | val ticket = when(type){
26 | IBuyTicket.TYPE_PLANE -> PlaneTicket()
27 | IBuyTicket.TYPE_GAO_TIE -> GaoTieTicket()
28 | IBuyTicket.TYPE_CAR -> CarTicket()
29 | else -> null
30 | }
31 |
32 | ticket?.getTicketMoney("深圳-广州", 137.5)
33 | }
34 |
35 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/jdk/ProxyHandler.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.jdk
2 |
3 | import java.lang.reflect.InvocationHandler
4 | import java.lang.reflect.Method
5 |
6 | /**
7 | * Desc : 动态代理
8 | * Author : Jetictors
9 | * Time : 2019-12-13 11:08
10 | * Email : zhengxcfutures@gmail.com
11 | * Version : v-1.0.1
12 | */
13 | class ProxyHandler(private val target : IDynamicTicket) : InvocationHandler{
14 |
15 | /**
16 | * [proxy] 代理对象
17 | * [method] 目标函数
18 | * [args] 目标函数的参数
19 | */
20 | override fun invoke(proxy: Any?, method: Method?, args: Array?): Any? {
21 |
22 | if (args == null) return null
23 |
24 | doBefore()
25 | val any = method?.invoke(target, args[0], args[1])
26 | doAfter()
27 |
28 | return any
29 | }
30 |
31 | private fun doBefore(){
32 | println("去代售点")
33 | }
34 |
35 | private fun doAfter(){
36 | println("买票成功了")
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/simple/demo1/ThirdFruitFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory.simple.demo1
2 |
3 | import com.kotlin.leran.design.factory.simple.demo1.Apple
4 | import com.kotlin.leran.design.factory.simple.demo1.Banana
5 | import com.kotlin.leran.design.factory.simple.demo1.Grape
6 | import com.kotlin.leran.design.factory.simple.demo1.IFruit
7 |
8 | /**
9 | * Desc : 静态工厂方法模式
10 | * Author : Jetictors
11 | * Time : 2019-12-17 16:41
12 | * Email : zhengxcfutures@gmail.com
13 | * Version : v-1.0.1
14 | */
15 | class ThirdFruitFactory{
16 |
17 | companion object{
18 | /**
19 | * 创建苹果
20 | */
21 | fun createApple() : IFruit {
22 | return Apple("green", 8.8)
23 | }
24 |
25 | /**
26 | * 创建香蕉
27 | */
28 | fun createBanana() : IFruit {
29 | return Banana(5.5)
30 | }
31 |
32 | /**
33 | * 创建葡萄
34 | */
35 | fun createGrape() : IFruit {
36 | return Grape(true, 12.8)
37 | }
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/observer/TestObserver.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.observer
2 |
3 | import com.kotlin.leran.design.observer.demo1.ConcreteObserver
4 | import com.kotlin.leran.design.observer.demo1.ConcreteSubject
5 |
6 | /**
7 | * Desc : 测试观察者模式
8 | * Author : Jetictors
9 | * Time : 2019-12-27 11:11
10 | * Email : zhengxcfutures@gmail.com
11 | * Version : v-1.0.1
12 | */
13 |
14 | class TestObserver{
15 |
16 | fun test(){
17 | testObserverDemo1()
18 | testObserverDemo2()
19 | }
20 |
21 | /**
22 | * 测试观察者概念demo
23 | */
24 | private fun testObserverDemo1(){
25 | val subject = ConcreteSubject()
26 | val observerFirst = ConcreteObserver("观察者对象1")
27 | val observerSecond = ConcreteObserver("观察者对象2")
28 |
29 | subject.attach(observerFirst)
30 | subject.attach(observerSecond)
31 | subject.notifyObserver()
32 |
33 | subject.detach(observerFirst)
34 | subject.notifyObserver()
35 | }
36 |
37 | /**
38 | * 测试观察者模式实例
39 | */
40 | private fun testObserverDemo2(){}
41 |
42 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/singleton/FirstInstance.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.singleton
2 |
3 | /**
4 | * Desc : 单列模式一(懒汉模式)
5 | * Author : Jetictors
6 | * Time : 2019-12-16 18:06
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 | class FirstInstance private constructor(){
11 |
12 | companion object{
13 |
14 | // 方式一: 直接使用公有变量的形式
15 | /*
16 | val sInstance : FirstInstance? = null
17 | get() {
18 | if (null == field){
19 | return FirstInstance()
20 | }
21 | return field
22 | }
23 | */
24 |
25 | // 方式二:使用私有变量+函数的形式
26 | private var sInstance : FirstInstance? = null
27 |
28 | fun getInstance() : FirstInstance?{
29 | if (null == sInstance){
30 | sInstance = FirstInstance()
31 | }
32 | return sInstance
33 | }
34 | }
35 |
36 | /**
37 | * 测试函数
38 | */
39 | fun testInstance(){
40 | println("${javaClass.simpleName}初始化成功,并调用了测试函数")
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/SealedClassDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 密封类详解
5 | * author : Jetictors
6 | * time : 2017/12/31 0:39
7 | * version : v1.0.1
8 | */
9 | sealed class SealedExpr{
10 | data class Person(val name : String, val age : Int) : SealedExpr()
11 | object Add : SealedExpr()
12 | companion object Minus : SealedExpr()
13 | }
14 |
15 | object NotANumber : SealedExpr()
16 |
17 | fun eval(expr: SealedExpr) = when(expr){
18 | is SealedExpr.Add -> println("is Add")
19 | is SealedExpr.Minus -> println("is Minus")
20 | is SealedExpr.Person -> println(SealedExpr.Person("Koltin",22))
21 | NotANumber -> TODO()
22 | }
23 |
24 | /**
25 | * 测试密封类其子类的扩展函数
26 | */
27 | fun SealedExpr.Add.add(num1 : Int, num2 : Int) : Int{
28 | return num1 + num2
29 | }
30 |
31 | class SealedClassDemo{
32 |
33 | fun test(){
34 | val mPerson1 = SealedExpr.Person("name1",22)
35 | println(mPerson1)
36 |
37 | val mPerson2 = SealedExpr.Person("name2",23)
38 | println(mPerson2)
39 |
40 | println(mPerson1.hashCode())
41 | println(mPerson2.hashCode())
42 |
43 | eval(SealedExpr)
44 |
45 | println(SealedExpr.Add.add(1,2))
46 | }
47 |
48 | }
49 |
50 |
51 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/NoteDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin语法之注释
5 | * author : Jetictors
6 | * time : 2017/9/1 00:50
7 | * version : 1.0.1
8 | */
9 | class NoteDemo{
10 |
11 | init {
12 | println("其实kotlin与java的注释是几乎相同的,都支持单行注释和多行注释(块注释).\n 不过与java不同的kotlin中的块注释可以级联")
13 | }
14 |
15 | private fun note1(){
16 | // 1. 单行注释
17 | println("单行注释写法:")
18 | println("两个斜杠开头表示单行注释('//')!")
19 | }
20 |
21 | private fun note2(){
22 | /*
23 | 2. 多行注释
24 | */
25 | println("多行注释的写法:")
26 | println("以斜杠加星号开头(/*),同时以星号加斜杠结尾(*/),中间这是要注释的代码块!")
27 | }
28 |
29 | private fun note3(){
30 | /*
31 | 第一层块注释
32 | /*
33 | 第二层块注释
34 | /*
35 | 第三层快注释
36 | 这种注释方式在java中是不支持的,但是在kotlin中是支持的。算是一个亮点吧(貌似意义不大)。
37 | */
38 | */
39 | */
40 | }
41 |
42 | /**
43 | * 函数注释
44 | * [a] 参数a
45 | * [b] 参数b
46 | */
47 | private fun note4(a : Int, b : Int){
48 | println("result = ${a + b}")
49 | }
50 |
51 | fun test(){
52 | note1()
53 | note2()
54 | note3()
55 | note4(1,2)
56 | }
57 |
58 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/DataClassDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 数据类
5 | * author : Jetictors
6 | * time : 2017/12/13 0:42
7 | * version : v1.0.1
8 | */
9 | data class Person(var param1: String = "param1",
10 | var param2: String = "param2",
11 | var param3 : String,
12 | var param4 : Long,
13 | var param5 : Int = 2,
14 | var param6 : String,
15 | var param7 : Float = 3.14f,
16 | var param8 : Int,
17 | var param9 : String){
18 | // exp
19 | }
20 |
21 | data class User(val name : String, val pwd : String)
22 |
23 | class DataClassDemo {
24 |
25 | fun test(){
26 | val mUser = User("kotlin","123456")
27 | println(mUser)
28 |
29 | val mNewUser = mUser.copy(name = "new Kotlin")
30 | println(mNewUser)
31 |
32 | val (name,pwd) = mUser
33 | println("name = $name \t pwd = $pwd")
34 |
35 | val pair = Pair(1,2) // 实例
36 | val triple = Triple(1,2,3) // 实例
37 | println("$pair \t $triple") // 打印:即调用了各自的toString()方法
38 | println(pair.toList()) // 转换成List集合
39 | println(triple.toList()) // 转换成List集合
40 | println(pair to 3) // Pair类特有: 其作用是把参数Pair类中的第二个参数替换
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/dynamic/cglib/TestCglibFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy.dynamic.cglib
2 |
3 | import net.sf.cglib.proxy.Enhancer
4 | import net.sf.cglib.proxy.MethodInterceptor
5 | import net.sf.cglib.proxy.MethodProxy
6 | import java.lang.reflect.Method
7 |
8 | /**
9 | * Desc : cglib动态代理
10 | * Author : Jetictors
11 | * Time : 2019-12-13 15:56
12 | * Email : zhengxcfutures@gmail.com
13 | * Version : v-1.0.1
14 | */
15 |
16 | class TestCglibFactory(private val target: Car) : MethodInterceptor{
17 |
18 | fun creator() : Car{
19 | val enhancer = Enhancer()
20 | // 设置需要代理的对象 : 目标类(target) , 也是父类
21 | enhancer.setSuperclass(target.javaClass)
22 | // 设置代理对象, 这是回调设计模式: 设置回调接口对象 :
23 | enhancer.setCallback(this)
24 | return enhancer.create() as Car
25 | }
26 |
27 | override fun intercept(proxy: Any?, method: Method?, args: Array?, p3: MethodProxy?): Any? {
28 |
29 | if (null == args || args.isEmpty()) return null
30 |
31 | doBefore()
32 | val any = method?.invoke(target, args[0], args[1])
33 | doAfter()
34 |
35 | return any
36 | }
37 |
38 | private fun doBefore(){
39 | println("去代售点")
40 | }
41 |
42 | private fun doAfter(){
43 | println("买票成功了")
44 | }
45 |
46 | }
--------------------------------------------------------------------------------
/KotlinLearn.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/ClassDemo1.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 类的声明
5 | * author : Jetictors
6 | * time : 2017/10/29 23:39
7 | * version : v1.0.1
8 | */
9 |
10 | class Test1(num : Int)
11 |
12 | // 因为是默认的可见性修饰符且不存在任何的注释符, 故而主构造函数constructor关键字可以省略
13 | class Test2(num: Int)
14 |
15 | class Test3 constructor(num : Int)
16 |
17 | class Test4 constructor(num: Int){
18 |
19 | init {
20 | println("num = $num")
21 | }
22 |
23 | constructor(num : Int, num2: Int) : this(num) {
24 | println(num + num2)
25 | }
26 | }
27 |
28 | class Test constructor(num1: Int = 10 , num2: Int = 20){
29 |
30 | init {
31 | println("num1 = $num1\t num2 = $num2")
32 | }
33 |
34 | constructor(num1 : Int = 1, num2 : Int = 2, num3 : Int = 3) : this(num1 , num2){
35 | println("num1 = $num1\t num2 = $num2 \t num3 = $num3")
36 | }
37 | }
38 |
39 | class Test5 (var num : Int){
40 | init {
41 | num = 5
42 | println("num = $num")
43 | }
44 | }
45 |
46 | // 类似下面两种情况的,都必须存在constructor关键字,并且在修饰符或者注释符后面。
47 | class Test6 private constructor(num: Int)
48 |
49 | // class Test7 @Inject constructor(num: Int)
50 |
51 |
52 | class ClassDemo1 {
53 |
54 | fun test(){
55 | var test = Test()
56 | var test1 = Test(1,2)
57 | var test2 = Test(4,5,6)
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/InfixFunDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function
2 |
3 | import java.math.BigDecimal
4 |
5 | /**
6 | * Desc : 中缀函数实例
7 | * Author : Jetictors
8 | * Time : 2019/9/17 14:53
9 | * Email : zhengxcfutures@gmail.com
10 | * Version : v-1.0.1
11 | */
12 |
13 | /**
14 | * 为Int定义一个加法的中缀函数
15 | * [num]
16 | */
17 | infix fun Int.add(num : Int) : Int{
18 | return this + num
19 | }
20 |
21 | /**
22 | * 为Int定义一个减法的中缀函数
23 | * [num]
24 | */
25 | infix fun Int.sub(num : Int) : Int{
26 | return this - num
27 | }
28 |
29 | /**
30 | * 为Int定义一个乘法的中缀函数
31 | * [num]
32 | */
33 | infix fun Int.mul(num : Int) : Int{
34 | return this * num
35 | }
36 |
37 | /**
38 | * 为Int定义一个除法的中缀函数
39 | * [num]
40 | */
41 | infix fun Int.div(num : Int) : String{
42 |
43 | val result = if (num == 0){
44 | 0.0
45 | }else{
46 | this / num.toDouble()
47 | }
48 |
49 | return BigDecimal(result).stripTrailingZeros().toPlainString()
50 | }
51 |
52 | class InfixFunDemo{
53 |
54 | infix fun testInFix(fix : String){
55 | println("a => $fix")
56 | }
57 |
58 |
59 |
60 | fun test(){
61 | println("add => ${3 add 3}")
62 | println("sub => ${3 sub 3}")
63 | println("mul => ${3 mul 3}")
64 | println("div => ${3 div 3}")
65 | println("div => ${3 div 0}")
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/adapter/TestAdapter.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.adapter
2 |
3 | import com.kotlin.leran.design.adapter.cls.ClsAdapter
4 | import com.kotlin.leran.design.adapter.default.MyAnimListener
5 | import com.kotlin.leran.design.adapter.obj.ObjAdaptee
6 | import com.kotlin.leran.design.adapter.obj.ObjAdapter
7 |
8 | /**
9 | * Desc : 适配器模式测试类
10 | * Author : Jetictors
11 | * Time : 2019-12-30 11:46
12 | * Email : zhengxcfutures@gmail.com
13 | * Version : v-1.0.1
14 | */
15 | class TestAdapter {
16 |
17 | fun test(){
18 | testClsAdapter()
19 | testDefaultAdapter()
20 | testObjAdapter()
21 | }
22 |
23 | /**
24 | * 缺省类适配器模式
25 | */
26 | private fun testClsAdapter(){
27 | val target = ClsAdapter()
28 | println(target.operatorFirst())
29 | println(target.operatorSecond())
30 | }
31 |
32 | /**
33 | * 测试缺省/模式的适配器模式
34 | */
35 | private fun testDefaultAdapter(){
36 | val listener = MyAnimListener()
37 | listener.onStart()
38 | listener.onResume()
39 | listener.onPause()
40 | listener.onEnd()
41 | listener.onRepeat()
42 | }
43 |
44 | /**
45 | * 测试对象类适配器模式
46 | */
47 | private fun testObjAdapter(){
48 | val adaptee = ObjAdaptee()
49 | val target = ObjAdapter(adaptee)
50 | println(target.operatorFirst())
51 | println(target.operatorSecond())
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/AbstractClassDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 抽象类详解
5 | * author : Jetictors
6 | * time : 2017/12/31 22:37
7 | * version : v1.0.1
8 | */
9 | open class Base{
10 | open fun initTest(){}
11 | }
12 |
13 | abstract class Language : Base(){
14 |
15 | // 自身的属性
16 | val TAG = this.javaClass.simpleName
17 |
18 | // 自身的函数
19 | fun test(){
20 | // exp
21 | }
22 |
23 | // 抽象属性
24 | abstract var name : String
25 |
26 | // 覆写父类的方法
27 | abstract override fun initTest()
28 |
29 | abstract class Name(){}
30 | }
31 |
32 | /**
33 | * 抽象类Language的实现类TestLanguageA
34 | */
35 | class TestLanguageA : Language(){
36 |
37 | override var name: String
38 | get() = "Kotlin"
39 | set(value){}
40 |
41 | override fun initTest() {
42 | println("我是$name")
43 | }
44 | }
45 |
46 | /**
47 | * 抽象类Language的实现类TestLanguageB
48 | */
49 | class TestLanguageB : Language(){
50 | override var name: String
51 | get() = "Java"
52 | set(value) {}
53 |
54 | override fun initTest() {
55 | println("我是$name")
56 | }
57 |
58 | }
59 |
60 | class AbstarctClassDemo {
61 |
62 | fun test(){
63 | // val mLanauage = Lanauage() 是错误的,因为抽象类不能直接被实例化
64 | val mLanauage : Language = TestLanguageB()
65 |
66 | val mTestA = TestLanguageA()
67 | val mTestB = TestLanguageB()
68 |
69 | println(mTestA.name)
70 | mTestA.initTest()
71 |
72 | println(mTestB.name)
73 | mTestB.initTest()
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/lambda/LambdaDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function.lambda
2 |
3 |
4 | /**
5 | * 描述 : Lambda表达式详解
6 | * author : Jetictors
7 | * time : 2018/3/21 23:50
8 | * version : v1.0.1
9 | */
10 |
11 | class LambdaDemo {
12 |
13 | fun test(){
14 | fun test(a : Int , b : (num1 : Int , num2 : Int) -> Int) : Int{
15 | return a + b.invoke(5,3)
16 | }
17 |
18 | println(test(10) { num1: Int, num2: Int -> num1 + num2})
19 |
20 | val arr = arrayOf(1,3,5,7,9)
21 |
22 | println(arr.filter { it < 2 }.component1())
23 |
24 | fun test1(num1 : Int, bool : (Int) -> Boolean) : Int{
25 | return if (bool(num1)){ num1 } else 0
26 | }
27 |
28 | println(test1(10) {it > 5})
29 | println(test1(4) {it > 5})
30 |
31 | val test1 = fun(x : Int , y : Int) = x + y
32 | val test2 = fun(x : Int , y : Int) : Int = x + y
33 | val test3 = fun(x : Int , y : Int) : Int{
34 | return x + y
35 | }
36 |
37 | println(test1(3,5))
38 | println(test2(4,6))
39 | println(test3(5,7))
40 |
41 | fun test(b : Int): () -> Int{
42 | var a = 3
43 | return fun() : Int{
44 | a++
45 | return a + b
46 |
47 | }
48 | }
49 |
50 | val t = test(3)
51 | println(t())
52 | println(t())
53 | println(t())
54 |
55 | var sum : Int = 0
56 | arr.filter { it < 7 }.forEach { sum += it }
57 |
58 | println(sum)
59 |
60 | val iop = fun Int.( other : Int) : Int = this + other
61 | println(2.iop(3))
62 | }
63 |
64 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/FieldDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : Kotlin属性/字段详解
5 | * author : Jetictors
6 | * time : 2018/1/29 1:01
7 | * version : v1.0.1
8 | */
9 |
10 | class Mime{
11 | val id : String = "123"
12 | var name : String? = "kotlin"
13 | var age : Int? = 22
14 | var sex : String? = "男"
15 | var weight : Float = 120.3f
16 | val s : Int by lazy { 10 }
17 |
18 | var test1 : String = ""
19 | get() = "123"
20 | set(value){field = value}
21 |
22 | val test2 : String
23 | get() = "123"
24 |
25 | private val size = 0
26 | val isEmpty : Boolean
27 | get() = this.size == 0
28 |
29 | val num = 2
30 | get() = if (field > 5) 10 else 0
31 |
32 | var str1 = "demo1"
33 | get() = field
34 | set(value){
35 | field = if (value.isNotEmpty()) value else "null"
36 | }
37 |
38 | var str2 = ""
39 | get() = "随意怎么修改都不会改变"
40 | set(value){
41 | field = if (value.isNotEmpty()) value else "null"
42 | }
43 |
44 | var str = "kotlin"
45 | private set
46 |
47 | }
48 |
49 | class FieldDemo {
50 |
51 | fun test(){
52 | val mime = Mime()
53 | println("id = ${mime.id} \t name = ${mime.name} \t age = ${mime.age} \t sex = ${mime.sex} \t weight = ${mime.weight}")
54 |
55 | println("isEmpty = ${mime.isEmpty}")
56 |
57 | println("num = ${mime.num}")
58 |
59 | println("str = ${mime.str1}")
60 | mime.str1 = ""
61 | println("str = ${mime.str1}")
62 | mime.str1 = "kotlin"
63 | println("str = ${mime.str1}")
64 |
65 | println("str = ${mime.str2}")
66 | mime.str2 = ""
67 | println("str = ${mime.str2}")
68 | mime.str2 = "kotlin"
69 | println("str = ${mime.str2}")
70 | }
71 |
72 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/VariableAndConstantDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin语法之变量和常量的使用
5 | * author : Jetictors
6 | * time : 2017/9/1 01:30
7 | * version : 1.0.1
8 | */
9 |
10 | class VariableAndConstantDemo{
11 |
12 | /**
13 | * 基础变量的定义及用法
14 | */
15 | private fun basisVariable() {
16 | //立即初始化
17 | var varA: Int = 10
18 |
19 | //推导出类型
20 | var varB = 5
21 |
22 | //没有初始化的时候,必须声明类型
23 | var varC: Float
24 | varC = 12.3f
25 | varC += 1
26 |
27 | println("varA => $varA \t varB => $varB \t varC => $varC")
28 |
29 | //立即初始化
30 | val valA: Int = 100
31 |
32 | //推导出类型
33 | val valB = 50
34 |
35 | //没有初始化的时候,必须声明类型
36 | val valC: Int
37 | valC = 1
38 | // val_c += 1 因为c是常量,所以这句代码是会报错的
39 |
40 | println("valA => $valA \t valB => $valB \t valC => $valC")
41 | }
42 |
43 | /**
44 | * 在类中,变量的定义及使用
45 | */
46 | private fun classVariable() {
47 |
48 | class Test1{
49 |
50 | // 定义属性, 再类中一定要初始化
51 | // var/val varA : Int 这样会报错,因为必须初始化,再函数以及顶层声明的时候没有此限制
52 | var varA = 0
53 | val valA = 0
54 |
55 | // 初始化
56 | init {
57 | varA = 10
58 | // valA = 0 为val类型不能更改。
59 |
60 | println("varA => $varA \t valA => $valA")
61 | }
62 | }
63 |
64 | Test1()
65 |
66 | class Test2{
67 |
68 | // 声明可空变量
69 |
70 | var varA : Int? = 0
71 | val valA : Int? = null
72 |
73 | init {
74 | varA = 10
75 | // val_a = 0 为val类型不能更改。
76 |
77 | println("varA => $varA \t valA => $valA")
78 | }
79 | }
80 |
81 | Test2()
82 | }
83 |
84 | fun test(){
85 | basisVariable()
86 | classVariable()
87 | }
88 | }
89 |
90 |
91 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/EnumDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 枚举类
5 | * author : Jetictors
6 | * time : 2017/10/31 23:45
7 | * version : v1.0.1
8 | */
9 |
10 |
11 | /**
12 | * 例:关于一个网络请求结果的枚举类
13 | */
14 | enum class State{
15 | /*
16 | NORMAL : 正常
17 | NO_DATA : 数据为空
18 | NO_INTERNET : 网络未连接
19 | ERROR : 错误
20 | OTHER : 其他
21 | */
22 |
23 | NORMAL,NO_DATA,NO_INTERNET,ERROR,OTHER
24 | }
25 |
26 | /**
27 | * 关于枚举常量匿名函数的枚举类
28 | */
29 | enum class ConsoleColor(var argb : Int){
30 | RED(0xFF0000){
31 | override fun print() {
32 | println("我是枚举常量 RED ")
33 | }
34 | },
35 | WHITE(0xFFFFFF){
36 | override fun print() {
37 | println("我是枚举常量 WHITE ")
38 | }
39 | },
40 | BLACK(0x000000){
41 | override fun print() {
42 | println("我是枚举常量 BLACK ")
43 | }
44 | },
45 | GREEN(0x00FF00){
46 | override fun print() {
47 | println("我是枚举常量 GREEN ")
48 | }
49 | };
50 |
51 | abstract fun print()
52 | }
53 |
54 | enum class Color(var argb : Int){
55 | RED(0xFF0000),
56 | WHITE(0xFFFFFF),
57 | BLACK(0x000000),
58 | GREEN(0x00FF00)
59 | }
60 |
61 | class EnumDemo{
62 |
63 | fun test(){
64 | println("name = " + Color.RED.name + "\tordinal = " + Color.RED.ordinal)
65 | println("name = " + Color.WHITE.name + "\tordinal = " + Color.WHITE.ordinal)
66 | println("name = " + Color.BLACK.name + "\tordinal = " + Color.BLACK.ordinal)
67 | println("name = " + Color.GREEN.name + "\tordinal = " + Color.GREEN.ordinal)
68 |
69 | println(enumValues().joinToString { it.name })
70 | println(enumValueOf("RED"))
71 |
72 | println(Color.valueOf("RED"))
73 | println(Color.values()[0])
74 | println(Color.values()[1])
75 | println(Color.values()[2])
76 | println(Color.values()[3])
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/InheritClsDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 继承类详解
5 | * author : Jetictors
6 | * time : 2018/1/22 23:14
7 | * version : v1.0.1
8 | */
9 |
10 | /**
11 | * 定义继承类的关键字为`open`
12 | */
13 | open class Demo{
14 |
15 | open var num = 3
16 |
17 | open fun foo() = "foo"
18 |
19 | open fun bar() = "bar"
20 |
21 | open fun test(){}
22 |
23 | open val valStr = "我是用val修饰的属性"
24 | }
25 |
26 | class DemoTest : Demo(){
27 |
28 | fun foo(str: String) : String{
29 | return str
30 | }
31 |
32 | override fun foo(): String {
33 | return super.foo()
34 | }
35 |
36 | override var num: Int = 10
37 |
38 | // override val valStr: String
39 | // get() = super.valStr
40 | //
41 | // override var valStr: String = ""
42 | // get() = super.valStr
43 | //
44 | // override val valStr: String = ""
45 |
46 | override var valStr: String = "abc"
47 | get() = super.valStr
48 | set(value){field = value}
49 | }
50 |
51 | class DemoTest2(override var num: Int, override val valStr: String) : Demo()
52 |
53 | open class A{
54 | open fun test1(){ println("基类A中的函数test1()") }
55 |
56 | open fun test2(){println("基类A中的函数test2()")}
57 | }
58 |
59 | interface B{
60 | fun test1(){ println("接口类B中的函数test1()") }
61 |
62 | fun test2(){println("接口类B中的函数test2()")}
63 | }
64 |
65 | class C : A(),B{
66 | override fun test1() {
67 | super.test1()
68 | super.test1()
69 | }
70 |
71 | override fun test2() {
72 | super.test2()
73 | super.test2()
74 | }
75 | }
76 |
77 | class InheritClsDemo{
78 |
79 | fun test(){
80 | println(DemoTest().num)
81 | println(DemoTest().foo())
82 | println(DemoTest().bar())
83 | println(DemoTest().foo("foo的重载函数"))
84 |
85 | println(DemoTest().num)
86 |
87 | println(DemoTest().valStr)
88 |
89 | val demo = DemoTest()
90 | demo.valStr = "1212121212"
91 | println(demo.valStr)
92 |
93 | val demo2 = DemoTest2(1,"构造函数中重写")
94 | println("num = ${demo2.num} \t valStr = ${demo2.valStr}")
95 | }
96 |
97 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/InnerClassDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * 描述 : 内部类
5 | * author : Jetictors
6 | * time : 2017/12/13 0:43
7 | * version : v1.0.1
8 | */
9 | class Other{ // 外部类
10 | val numOther = 1
11 | lateinit var listener : OnClickListener
12 |
13 | class Nested { // 嵌套类
14 | fun init(){
15 | println("init")
16 | }
17 | }
18 |
19 | fun partMethod(){
20 | var name : String = "partMethod"
21 |
22 | class Part{
23 | var numPart : Int = 2
24 |
25 | fun test(){
26 | name = "demo1"
27 | numPart = 5
28 | println("我是局部类中的方法")
29 | }
30 | }
31 |
32 | val part = Part()
33 | println("name = $name \t numPart = " + part.numPart + "\t numOther = $numOther")
34 | part.test()
35 | println("name = $name \t numPart = " + part.numPart + "\t numOther = $numOther")
36 | }
37 |
38 | inner class InnerClass{
39 | val name = "InnerClass"
40 | fun init(){
41 | println("我是内部类")
42 | }
43 | }
44 |
45 | fun setOnClickListener(listener : OnClickListener){
46 | this.listener = listener
47 | }
48 |
49 | fun setOnClickListener2(listener: OnClickListener) : OnClickListener{
50 | this.listener = listener
51 | listener.onItemClick("sssss")
52 | return listener
53 | }
54 |
55 | fun testListener(){
56 | listener.onItemClick("我是匿名内部类的测试方法")
57 | }
58 |
59 | fun testListener2(){
60 | listener.onItemClick("sss")
61 | }
62 | }
63 |
64 | interface OnClickListener{
65 | fun onItemClick(str : String)
66 | }
67 |
68 | class InnerClassDemo {
69 |
70 | fun test() {
71 | // 测试嵌套类
72 | Other.Nested().init() // 调用格式为:外部类.嵌套类().嵌套类方法/属性
73 |
74 | // 测试内部类
75 | Other().InnerClass().init() // 调用格式为:外部类().内部类().内部类方法/属性
76 |
77 | // 测试局部类
78 | Other().partMethod()
79 |
80 | // 测试匿名内部类
81 | val other = Other()
82 | other.setOnClickListener(object : OnClickListener {
83 | override fun onItemClick(str: String) {
84 | // todo
85 | println(str)
86 | }
87 | })
88 | }
89 |
90 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/BasisFunctionDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function
2 |
3 |
4 | /**
5 | * 描述 : Kotlin语法之基本函数使用
6 | * author : Jetictors
7 | * time : 2017/10/9 22:59
8 | * version : 1.0.1
9 | */
10 |
11 | open class A{
12 | open fun foo(i : Int = 10){}
13 | }
14 |
15 | class B : A(){
16 | override fun foo(i: Int) {
17 | super.foo(i)
18 | println(i)
19 | }
20 | }
21 |
22 | class BasisFunctionDemo {
23 |
24 | /**
25 | * 函数的定义
26 | */
27 | private fun funBasis() {
28 | println("我是函数funBasis")
29 | }
30 |
31 | private fun unitFun() : Unit{
32 | println("我是返回值为Unit的函数,Unit可省略")
33 |
34 | // return Unit 可省略
35 | // 或者 return 可省略
36 | }
37 |
38 |
39 | /**
40 | * 具有默认参数的函数
41 | */
42 | private fun defArgs(numA : Int = 1, numB : Float = 2f, numC : Boolean = false){
43 | println("numA = $numA \t numB = $numB \t numC = $numC")
44 | }
45 |
46 | /**
47 | * 具有参数的函数定义
48 | */
49 | private fun funArgs(numA : Int, numB : Float){
50 | println("numA = $numA \t numB = $numB")
51 | }
52 |
53 | // 无参数的情况
54 | private fun test1() = 2
55 |
56 | // 有参数的情况
57 | private fun test2(num : Int) = num * 2 // 自动推断为:返回类型为Int
58 |
59 | // 或者
60 | private fun test3(x : Float, y : Int = 2) = x * y // 和默认参数一起使用,返回值为Int型
61 |
62 | /**
63 | * 命名参数的函数
64 | */
65 | private fun callFun(str : String,
66 | isTrue : Boolean = false,
67 | numA : Int = 2,
68 | numB: Float = 2.0f,
69 | numC : Int = 2){}
70 |
71 | private fun varargFun(numA: Int, vararg str : String){
72 |
73 | // 遍历
74 | for (s in str) {
75 |
76 | }
77 |
78 | // 获取元素
79 | // str[index]
80 | // str.component1() ... str.component5()
81 |
82 | // 或者其高阶函数用法
83 | // str.map { }
84 | // str.filter { }
85 | // str.sortBy { }
86 |
87 | }
88 |
89 | fun test(){
90 | // 函数的使用
91 | funBasis()
92 |
93 | funArgs(2,10f)
94 |
95 | defArgs()
96 | defArgs(1,10f,true)
97 |
98 | B().foo()
99 |
100 | println(test1())
101 | println(test2(2))
102 | println(test3(2f))
103 | }
104 |
105 | }
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/proxy/TestProxy.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.proxy
2 |
3 | import com.kotlin.leran.design.proxy.dynamic.cglib.Car
4 | import com.kotlin.leran.design.proxy.dynamic.cglib.TestCglibFactory
5 | import com.kotlin.leran.design.proxy.dynamic.jdk.*
6 | import com.kotlin.leran.design.proxy.statics.demo1.Driver
7 | import com.kotlin.leran.design.proxy.statics.demo1.FirstDriver
8 | import com.kotlin.leran.design.proxy.statics.demo1.MoneyProxy
9 | import com.kotlin.leran.design.proxy.statics.demo2.PlaneProxy
10 | import com.kotlin.leran.design.proxy.statics.demo2.RailwayProxy
11 | import com.kotlin.leran.design.proxy.statics.demo2.User
12 | import java.lang.reflect.Proxy
13 |
14 | /**
15 | * Desc : 测试代理模式
16 | * Author : Jetictors
17 | * Time : 2019-12-27 17:04
18 | * Email : zhengxcfutures@gmail.com
19 | * Version : v-1.0.1
20 | */
21 | class TestProxy{
22 |
23 | fun test(){
24 | testStaticsProxy()
25 | testJdkDynamicProxy()
26 | testCglibDynamicProxy()
27 | }
28 |
29 | /**
30 | * 测试静态代理
31 | */
32 | private fun testStaticsProxy(){
33 | val user = User()
34 | val planeProxy = PlaneProxy(user)
35 | planeProxy.buyTicket("深圳-重庆", 783.56)
36 |
37 | val railwayProxy = RailwayProxy(user)
38 | railwayProxy.buyTicket("广州南-重庆西", 428.23)
39 |
40 | val driver = Driver()
41 | val driverProxy2 = MoneyProxy(driver)
42 | driverProxy2.giveMoney(5,13)
43 |
44 | val firstDriver = FirstDriver()
45 | firstDriver.giveMoney(7,12)
46 | }
47 |
48 | /**
49 | * 测试动态代理
50 | */
51 | private fun testJdkDynamicProxy(){
52 | val railway = Railway()
53 | var handler = ProxyHandler(railway)
54 | val railwayProxy = Proxy.newProxyInstance(railway.javaClass.classLoader,
55 | railway.javaClass.interfaces, handler) as IDynamicTicket
56 | railwayProxy.buyTicket("广州南-重庆西", 428.34)
57 |
58 | val plane = Plane()
59 | handler = ProxyHandler(plane)
60 | val planeProxy = Proxy.newProxyInstance(plane.javaClass.classLoader,
61 | plane.javaClass.interfaces, handler) as IDynamicTicket
62 | planeProxy.buyTicket("深圳-重庆", 1028.34)
63 |
64 | val boat = Boat()
65 | handler = ProxyHandler(boat)
66 | val boatProxy = Proxy.newProxyInstance(boat.javaClass.classLoader,
67 | boat.javaClass.interfaces, handler) as IDynamicTicket
68 | boatProxy.buyTicket("深圳-香港", 167.34)
69 | }
70 |
71 | /**
72 | * 测试动态代理
73 | */
74 | private fun testCglibDynamicProxy(){
75 | val car = Car()
76 | val carProxy = TestCglibFactory(car).creator()
77 | carProxy.buyCarTicket("深圳-广州", 137.5)
78 | }
79 |
80 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/design/factory/TestFactory.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.design.factory
2 |
3 | import com.kotlin.leran.design.factory.method.demo1.FactoryA
4 | import com.kotlin.leran.design.factory.method.demo1.FactoryB
5 | import com.kotlin.leran.design.factory.method.demo2.AmericaFactory
6 | import com.kotlin.leran.design.factory.method.demo2.HuaweiFactory
7 | import com.kotlin.leran.design.factory.method.demo2.XiaoMiFactory
8 | import com.kotlin.leran.design.factory.simple.demo1.FirstFruitFactory
9 | import com.kotlin.leran.design.factory.simple.demo1.SecondFruitFactory
10 | import com.kotlin.leran.design.factory.simple.demo1.ThirdFruitFactory
11 | import com.kotlin.leran.design.factory.simple.demo2.ProduceFactory
12 | import com.kotlin.leran.design.factory.simple.demo3.ConcreteProduce
13 |
14 | /**
15 | * Desc : 测试工厂模式
16 | * Author : Jetictors
17 | * Time : 2019-12-27 11:11
18 | * Email : zhengxcfutures@gmail.com
19 | * Version : v-1.0.1
20 | */
21 |
22 | class TestFactory{
23 |
24 | fun test(){
25 | testSimpleDemo1()
26 | testSimpleDemo2()
27 | testSimpleDemo3()
28 |
29 | testMethodDemo1()
30 | testMethodDemo2()
31 |
32 |
33 | }
34 |
35 | private fun testSimpleDemo1(){
36 | // 普通工厂测试
37 | val firstFruit = FirstFruitFactory().createFactory("apple")
38 | firstFruit?.harvest()
39 |
40 | // 多个工厂方法测试
41 | val secondFruit = SecondFruitFactory().createBanana()
42 | secondFruit.harvest()
43 |
44 | // 静态工厂方法测试
45 | val thirdFruit = ThirdFruitFactory.createGrape()
46 | thirdFruit.harvest()
47 | }
48 |
49 | /**
50 | * 省略了抽象角色的工厂类 测试
51 | */
52 | private fun testSimpleDemo2(){
53 | val firstProduce = ProduceFactory().createProduce()
54 | firstProduce.update()
55 | }
56 |
57 | /**
58 | * 抽象角色、工厂类、具体角色合并到一起 即自身创建自身(外部不用new创建) 测试
59 | */
60 | private fun testSimpleDemo3(){
61 | val secondProduce = ConcreteProduce.createProduce()
62 | secondProduce.show()
63 | }
64 |
65 | /**
66 | * 测试简易工厂方法模式
67 | */
68 | private fun testMethodDemo1(){
69 | val factoryA = FactoryA()
70 | val produceA = factoryA.createProduce()
71 | produceA.showTest("ProduceA")
72 |
73 | val factoryB = FactoryB()
74 | val produceB = factoryB.createProduce()
75 | produceB.showTest("ProduceB")
76 | }
77 |
78 | /**
79 | * 测试复杂工厂方法模式
80 | */
81 | private fun testMethodDemo2(){
82 | val huaweiFactory = HuaweiFactory()
83 | val huaweiPhone = huaweiFactory.createPhone("P30 mate", "2019-9-12")
84 | huaweiPhone.aboutSelf()
85 |
86 | val xiaoMiFactory = XiaoMiFactory()
87 | val xiaoMiPhone = xiaoMiFactory.createPhone("Xiao Mi 9", "2019-9-12")
88 | xiaoMiPhone.aboutSelf()
89 |
90 | val americaFactory = AmericaFactory()
91 | val applePhone = americaFactory.createPhone("iPhone 11 max ", "2019-9-12")
92 | applePhone.aboutSelf()
93 | }
94 |
95 |
96 |
97 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/TestApplication.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran
2 |
3 | import com.kotlin.leran.basis.*
4 | import com.kotlin.leran.cls.TypealiasDemo
5 | import com.kotlin.leran.cls.classDemo.*
6 | import com.kotlin.leran.coroutines.Basis
7 | import com.kotlin.leran.design.adapter.TestAdapter
8 | import com.kotlin.leran.design.factory.TestFactory
9 | import com.kotlin.leran.design.observer.TestObserver
10 | import com.kotlin.leran.design.policy.TestPolicy
11 | import com.kotlin.leran.design.policy.demo.IBuyTicket
12 | import com.kotlin.leran.function.BasisFunctionDemo
13 | import com.kotlin.leran.function.InfixFunDemo
14 | import com.kotlin.leran.function.SeniorFunctionDemo
15 | import com.kotlin.leran.function.lambda.LambdaDemo
16 | import com.kotlin.leran.other.CollectionDemo
17 | import com.kotlin.leran.other.OperaCollectionDemo
18 |
19 | /**
20 | * Desc : 程序入口类
21 | * Author : Jetictors
22 | * Time : 2019/9/16 14:28
23 | * Email : zhengxcfutures@gmail.com
24 | * Version : v-1.0.1
25 | */
26 | fun main(args: Array) {
27 |
28 | // 测试 HelloWorld
29 | HelloWorld().test()
30 |
31 | // 测试 变量
32 | VariableAndConstantDemo().test()
33 |
34 | // 测试 常量
35 | Constant().test()
36 |
37 | // 测试 注释
38 | NoteDemo().test()
39 |
40 | // 测试 数据类型
41 | DataTypeDemo().test()
42 |
43 | // 测试 控制语句(if、for、while...)
44 | ControlStatementDemo().test()
45 |
46 | // 测试 空安全
47 | NullAndNullCheckDemo().test()
48 |
49 | // 测试 操作符
50 | OperatorStringDemo().test()
51 |
52 | // 测试 函数基础
53 | BasisFunctionDemo().test()
54 |
55 | // 测试 类的声明
56 | ClassDemo1().test()
57 |
58 | // 测试 属性与字段
59 | FieldDemo().test()
60 |
61 | // 测试 抽象类
62 | AbstarctClassDemo().test()
63 |
64 | // 测试 数据类
65 | DataClassDemo().test()
66 |
67 | // 测试 枚举类
68 | EnumDemo().test()
69 |
70 | // 测试 内部类
71 | InnerClassDemo().test()
72 |
73 | // 测试 密封类
74 | SealedClassDemo().test()
75 |
76 | // 测试 继承
77 | InheritClsDemo().test()
78 |
79 | // 测试 接口
80 | InterfaeDemo().test()
81 |
82 | // 测试 类型别名
83 | TypealiasDemo().test()
84 |
85 | // 测试 Lambda语法
86 | LambdaDemo().test()
87 |
88 | // 测试 中缀函数
89 | val infixDemo = InfixFunDemo()
90 | infixDemo testInFix("测试中缀函数")
91 | infixDemo.test()
92 |
93 | // 测试高阶函数
94 | SeniorFunctionDemo().test()
95 |
96 | // 测试 集合初始化
97 | CollectionDemo().test()
98 |
99 | // 测试 集合的各种操作
100 | OperaCollectionDemo().test()
101 |
102 | // 测试协程
103 | // testCoroutine()
104 |
105 | // 测试工厂模式
106 | TestFactory().test()
107 |
108 | // 测试 适配器模式
109 | TestAdapter().test()
110 |
111 | // 测试代理模式
112 | TestObserver().test()
113 |
114 | // 测试策略模式
115 | TestPolicy().test(IBuyTicket.TYPE_PLANE)
116 |
117 | // 测试观察者模式
118 | TestObserver().test()
119 |
120 | }
121 |
122 | /**
123 | * 测试协程
124 | */
125 | private suspend fun testCoroutine(){
126 | Basis().test()
127 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/TypealiasDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls
2 |
3 | /**
4 | * 描述 : 类型别名讲解
5 | * author : Jetictors
6 | * time : 2019/3/16 17:49
7 | * version : 1.0.1
8 | */
9 |
10 | typealias First = TypeAliasDemoTestFirst
11 | typealias Second = TypeAliasDemoTestSecond
12 |
13 | typealias NestA = DemoClassTestNest.A
14 | typealias NestB = DemoClassTestNest.B
15 |
16 | typealias InnerA = DemoClassTestInner.A
17 | typealias InnerB = DemoClassTestInner.B
18 |
19 | typealias MutListData = MutableList>
20 | typealias MapModelData = MutableMap>
21 |
22 | // 定义一个返回值为Boolean类型的函数为另一个函数的参数,把这个函数参数定义为`Predicate`的别名
23 | typealias Predicate = (T) -> Boolean
24 |
25 | // 定义的高阶函数
26 | fun foo1(p : Predicate) = p(2)
27 | fun foo2(p : Predicate) = p("demo1")
28 |
29 | class DemoClassTestNest{
30 | class A{
31 | fun show(){
32 | println("name : ${this.javaClass.simpleName}")
33 | }
34 | }
35 |
36 | class B{
37 | fun show(){
38 | println("name : ${this.javaClass.simpleName}")
39 | }
40 | }
41 | }
42 |
43 | class DemoClassTestInner{
44 | class A{
45 | fun show(){
46 | println("name : ${this.javaClass.simpleName}")
47 | }
48 | }
49 |
50 | class B{
51 | fun show(){
52 | println("name : ${this.javaClass.simpleName}")
53 | }
54 | }}
55 |
56 | class TypeAliasDemoTestFirst{
57 | fun show(){
58 | println("name : ${this.javaClass.simpleName}")
59 | }
60 | }
61 |
62 | class TypeAliasDemoTestSecond{
63 | fun show(){
64 | println("name : ${this.javaClass.simpleName}")
65 | }
66 | }
67 |
68 | data class TestBean(val id : Int,
69 | val name : String,
70 | val `package` : String)
71 |
72 | data class BaseModel(val code : Int,
73 | val msg : String,
74 | val data : T){
75 | override fun toString(): String {
76 | return "BaseModel(code=$code, msg='$msg', data=$data)"
77 | }
78 | }
79 |
80 | class TypealiasDemo {
81 |
82 | fun test() {
83 | val first = First()
84 | first.show()
85 |
86 | val second = Second()
87 | second.show()
88 |
89 | val nestA = NestA()
90 | nestA.show()
91 |
92 | val nestB = NestB()
93 | nestB.show()
94 |
95 | val innerA = InnerA()
96 | innerA.show()
97 |
98 | val innerB = InnerB()
99 | innerB.show()
100 |
101 | val data: MutListData = mutableListOf()
102 | val item1 = mutableListOf(1, 3, 5, 7)
103 | val item2 = mutableListOf(2, 4, 6, 8)
104 | data.add(item1)
105 | data.add(item2)
106 |
107 | data.asSequence().flatMap { it.asSequence() }.forEach { print("value : $it \t") }
108 |
109 | val dataModel: MapModelData = mutableMapOf()
110 | val model1 = BaseModel(1, "demo1 1", 1)
111 | val model2 = BaseModel(2, "test2", 2)
112 | dataModel.put("1", model1)
113 | dataModel.put("2", model2)
114 |
115 | dataModel.forEach { key, value ->
116 | println("key : $key value : ${value.toString()}")
117 | }
118 |
119 | // 条件,即函数参数为{it > 0},返回值时Boolean类型,其这里的it指的就是泛型T,确定为了Int型
120 | val f1: (Int) -> Boolean = { it > 0 }
121 | // 即把2带入foo1函数中,经过上面的条件,判断出 2 > 0 故而应该输出为true
122 | println(foo1(f1))
123 |
124 | val f2: (String) -> Boolean = { it == "xxx" }
125 | println(foo2(f2)) //这里输出为false, 很显然,"demo1" != "xxx"
126 | }
127 |
128 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/other/CollectionDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.other
2 |
3 | /**
4 | * 描述 : 集合详解
5 | * author : Jetictors
6 | * time : 2018/3/25 22:16
7 | * version : v1.0.1
8 | */
9 |
10 | class CollectionDemo{
11 |
12 | private fun mapDemo() {
13 |
14 | val emptyMap = emptyMap()
15 | val sortedMap = sortedMapOf()
16 | val map1 = mapOf("key1" to 2 , "key1" to 3)
17 | val map2 = mapOf(1 to "value1" , 2 to "value2")
18 | val mutableMap = mutableMapOf("key1" to 2 , "key1" to 3)
19 | val hashMap = hashMapOf("key1" to 2 , "key1" to 3)
20 |
21 | map2.forEach{
22 | key,value -> println("$key \t $value")
23 | }
24 |
25 | val map = mapOf("key1" to 2 , "key1" to 3 , "key1" to "value1" , "key2" to "value2")
26 |
27 | map.forEach{
28 | key,value -> println("$key \t $value")
29 | }
30 |
31 | map.forEach{
32 | _ , value -> println("$value")
33 | }
34 | }
35 |
36 | private fun setDemo() {
37 | val emptySet = emptySet()
38 | val hashSet = hashSetOf()
39 | val sortedSet = sortedSetOf()
40 | val set1 = setOf(1,2,"3","4","2",1,2,3,4,5)
41 | val mutableSet1 = mutableSetOf(1,2,"3","4","2",1,2,3,4,5)
42 |
43 | for (value in set1){
44 | print("$value \t")
45 | }
46 |
47 | println("\n")
48 | }
49 |
50 | private fun listDemo(){
51 | val emptyArray = emptyArray() // 创建空数组
52 | val arr = arrayOf("1",2,3,4)
53 |
54 | for (index in arr){
55 | print("$index \t")
56 | }
57 |
58 | arr.forEach { }
59 |
60 | arr.reverse()
61 | for (any in arr) {
62 | print("$any \t")
63 | }
64 | val emptyList = emptyList() // 创建空List
65 | val list1 = listOf(1,2,2,4,5)
66 | val list2 = listOf(arr)
67 | val list3 = listOf("1","2","3","4","5")
68 |
69 | val list : ArrayList // 这里的ArrayList<>和Java里面的ArrayList<>一致
70 |
71 | for (index in list1){
72 | print("$index \t")
73 | }
74 |
75 | println("\n")
76 |
77 | // 集合协变
78 | open class Person(val name : String , val age : Int){
79 | override fun toString(): String {
80 | return "Person(name='$name', age=$age)"
81 | }
82 | }
83 |
84 | class Student(name: String, age : Int, cls : String) : Person(name, age)
85 |
86 | val listPerson: List
87 | val listStudent : List = listOf(Student("张三",12,"一班"),Student("王五",20,"二班"))
88 | listPerson = listStudent
89 |
90 | listPerson.forEach { println(it.toString()) }
91 |
92 | val mutableListPerson: MutableList
93 | val mutableListStudent : List = listOf(Student("张三",12,"一班"),Student("王五",20,"二班"))
94 | mutableListPerson = mutableListStudent.toMutableList()
95 | mutableListPerson.add(Person("a",15))
96 | mutableListPerson.add(Person("b",45))
97 |
98 | mutableListPerson.forEach { println(it.toString()) }
99 | }
100 |
101 |
102 | private fun mutableListDemo(){
103 | val arr = arrayOf("1",2,3,4)
104 | val mutableList1 = mutableListOf(1,2,"3",4,"5") // 随意创建
105 | val mutableList2 = mutableListOf("1","2","3","4","5") // 确定元素的值类型
106 | val mutableList3 = mutableListOf(arr) // 可传入一个数组
107 | val mutableList : ArrayList // 这里的ArrayList<>和Java里面的ArrayList一致
108 |
109 | mutableList1.add("6") // 添加元素
110 | mutableList1.add("7")
111 | mutableList1.remove(1) // 删除某一元素
112 |
113 | // 遍历
114 | for(index in mutableList1){
115 | print("$index \t")
116 | }
117 |
118 | mutableList1.clear() // 清空集合
119 |
120 | println("\n")
121 | }
122 |
123 | fun test(){
124 | listDemo()
125 | mutableListDemo()
126 | setDemo()
127 | mapDemo()
128 | }
129 |
130 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/cls/classDemo/InterfaceDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.cls.classDemo
2 |
3 | /**
4 | * Desc : 接口使用
5 | * Author : Jetictors
6 | * Time : 2019/9/16 16:46
7 | * Email : zhengxcfutures@gmail.com
8 | * Version : v-1.0.1
9 | */
10 |
11 | /**
12 | * 接口声明
13 | */
14 | interface Demo1Interface{
15 | // 定义的方法
16 | fun fun1()
17 | }
18 |
19 | /**
20 | * 接口的实现类
21 | */
22 | class Demo1 : Demo1Interface {
23 | override fun fun1() {
24 | println("我是接口中的fun1方法")
25 | }
26 | }
27 |
28 | /**
29 | * 接口的方法使用
30 | */
31 | interface Demo2Interface{
32 |
33 | /**
34 | * 定义一个无参数无返回值的方法
35 | */
36 | fun fun1()
37 |
38 | /**
39 | * 定义一个有参数的方法
40 | */
41 | fun fun2(num: Int)
42 |
43 | /**
44 | * 定义一个有参数有返回值的方法
45 | */
46 | fun fun3(num: Int) : Int
47 |
48 | // 下面的两个方法是有结构体, 故可以不重写
49 |
50 | /**
51 | * 定义一个无参数有返回值的方法
52 | */
53 | fun fun4() : String{
54 | return "fun4"
55 | }
56 |
57 | /**
58 | * 定义一个无结构体函数,大括号是可以省略的
59 | */
60 | fun fun5(){
61 | // 如果函数中不存在表达式,大括号可以省略。
62 | // 如fun1一样
63 | }
64 | }
65 |
66 | class Demo2 : Demo2Interface{
67 |
68 | override fun fun1() {
69 | println("我是fun1()方法")
70 | }
71 |
72 | override fun fun2(num: Int) {
73 | println("我是fun2()方法,我的参数是$num")
74 | }
75 |
76 | override fun fun3(num: Int): Int {
77 | println("我是fun3()方法,我的参数是$num,并且返回一个Int类型的值")
78 | return num + 3
79 | }
80 |
81 | override fun fun4(): String {
82 | println("我是fun4()方法,并且返回一个String类型的值")
83 |
84 | /*
85 | 接口中的fun4()方法默认返回”fun4“字符串.
86 | 可以用super.fun4()返回默认值
87 | 也可以不用super关键字,自己返回一个字符串
88 | */
89 | return super.fun4()
90 | }
91 |
92 | /*
93 | 接口中的fun5()带有结构体,故而可以不用重写,
94 | fun4()同样
95 | */
96 | // override fun fun5() {
97 | // super.fun5()
98 | // }
99 | }
100 |
101 | /**
102 | * 接口中的属性使用
103 | */
104 | interface Demo3Interface{
105 | val num1: Int
106 |
107 | val num2 : Int
108 |
109 | // 声明比那俩和提供默认值
110 | // 注意: val num3: Int = 3 这种方式不提供,为直接报错的
111 | val num3: Int
112 | get() = 3
113 |
114 | val num4: Int
115 | }
116 |
117 | class Demo3(override val num1: Int, override val num2: Int) : Demo3Interface{
118 |
119 | // 提供访问器实现
120 | override val num3: Int
121 | get() = super.num3
122 |
123 | // 手动赋值
124 | override var num4: Int = 4
125 |
126 | fun sum() : Int{
127 | return num1 + num2
128 | }
129 |
130 | fun result() : Int{
131 | return num3 + num4
132 | }
133 | }
134 |
135 | /**
136 | * 接口的冲突问题解决
137 | */
138 | interface Demo4InterfaceOne{
139 | fun fun1(){
140 | println("我是Demo4InterfaceOne中的fun1()")
141 | }
142 |
143 | fun fun2(){
144 | println("我是Demo4InterfaceOne中的fun2()")
145 | }
146 | }
147 |
148 | interface Demo4InterfaceTwo{
149 | fun fun1(){
150 | println("我是Demo4InterfaceTwo中的fun1()")
151 | }
152 |
153 | fun fun2(){
154 | println("我是Demo4InterfaceTwo中的fun2()")
155 | }
156 | }
157 |
158 | class Demo4 : Demo4InterfaceOne,Demo4InterfaceTwo{
159 |
160 | override fun fun1() {
161 | super.fun1()
162 | super.fun1()
163 | }
164 |
165 | override fun fun2() {
166 | super.fun2()
167 | super.fun2()
168 | }
169 |
170 | }
171 |
172 | class InterfaeDemo{
173 |
174 | fun test(){
175 | val demo1 = Demo1()
176 | demo1.fun1()
177 |
178 | val demo2 = Demo2()
179 | demo2.fun1()
180 | demo2.fun2(5)
181 | println(demo2.fun3(10))
182 | println(demo2.fun4())
183 |
184 | //可以不重写该方法直接调用
185 | demo2.fun5()
186 |
187 | val demo = Demo3(1,2)
188 | println(demo.sum())
189 |
190 | println(demo.result())
191 |
192 | // 在这里也可以改变接口属性的值
193 | demo.num4 = 10
194 | println(demo.result())
195 |
196 | val demo4 = Demo4()
197 | demo4.fun1()
198 | demo4.fun2()
199 | }
200 |
201 | }
202 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/coroutines/Basis.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.coroutines
2 |
3 | import kotlinx.coroutines.*
4 |
5 |
6 | /**
7 | * Desc : 协程基础
8 | * Author : Jetictors
9 | * Time : 2019/10/9 11:20
10 | * Email : zhengxcfutures@gmail.com
11 | * Version : v-1.0.1
12 | */
13 | class Basis{
14 |
15 | suspend fun test(){
16 | // first()
17 | // second()
18 | // third()
19 | // fourth()
20 | // five()
21 | // six()
22 | // seven()
23 | // eight()
24 | // nine()
25 | // newNine()
26 | ten()
27 | newTen()
28 | }
29 |
30 | /**
31 | * 第一个协程程序
32 | */
33 | private fun first(){
34 | GlobalScope.launch {
35 | delay(1000)
36 | println("协程")
37 | }
38 | println("kotlin")
39 | Thread.sleep(2000)
40 | }
41 |
42 | /**
43 | * 用Thread替换协程,达到相同的效果
44 | */
45 | private fun second(){
46 | Thread{
47 | Thread.sleep(1000)
48 | println("协程")
49 | }.start()
50 | println("kotlin")
51 | Thread.sleep(2000)
52 | }
53 |
54 | /**
55 | * 桥接阻塞
56 | */
57 | private fun third(){
58 | GlobalScope.launch {
59 | delay(1000)
60 | println("协程")
61 | }
62 | println("kotlin")
63 | runBlocking {
64 | delay(2000)
65 | }
66 | }
67 |
68 | /**
69 | * 优化桥接阻塞函数,更符合开发习惯
70 | */
71 | private fun fourth() = runBlocking {
72 | GlobalScope.launch {
73 | delay(1000)
74 | println("协程")
75 | }
76 | println("kotlin")
77 | delay(2000)
78 | }
79 |
80 | /**
81 | * 等待一个作业
82 | */
83 | private suspend fun five(){
84 |
85 | val job = GlobalScope.launch {
86 | delay(1000)
87 | println("协程")
88 | }
89 | println("kotlin")
90 | job.join()
91 |
92 | }
93 |
94 | /**
95 | * 结构化并发
96 | */
97 | private fun six() = runBlocking {
98 | launch {
99 | delay(1000)
100 | println("协程")
101 | }
102 | println("Kotlin")
103 | }
104 |
105 | /**
106 | * 作用域构建器
107 | */
108 | private fun seven() = runBlocking {
109 | launch {
110 | delay(1000)
111 | println("Task from runBlocking")
112 | }
113 |
114 | coroutineScope{
115 | launch {
116 | delay(1500)
117 | println("Task from nested launch")
118 | }
119 |
120 | delay(500)
121 | println("Task from coroutine scope")
122 | }
123 |
124 | println("Coroutine scope is over")
125 | }
126 |
127 | /**
128 | * 函数重构使用
129 | */
130 | private fun eight() = runBlocking {
131 | launch { doWorld("协程") }
132 | println("kotlin")
133 | }
134 |
135 | /**
136 | * 测试协程的轻量级
137 | */
138 | private fun nine() = runBlocking {
139 | /*
140 | repeat函数是一个高阶函数,即循环作一件事
141 | [times] 循环次数
142 | [action] 动作(事情)
143 | */
144 | repeat(100_000){
145 | launch {
146 | delay(1000)
147 | print(".")
148 | }
149 | }
150 | }
151 |
152 | /**
153 | * 用线程作对比
154 | */
155 | private fun newNine(){
156 | repeat(100_000){
157 | Thread {
158 | print(".")
159 | }.start()
160 | }
161 | }
162 |
163 | private fun ten(){
164 |
165 | println("start")
166 |
167 | run{
168 | repeat(50){
169 | if (it == 20) return@repeat
170 | println("running $it")
171 | }
172 | }
173 |
174 | println("stop")
175 | }
176 |
177 | private fun newTen(){
178 | println("start")
179 |
180 | run{
181 | repeat(50){
182 | if (it == 20) return@run
183 | println("running $it")
184 | }
185 | }
186 |
187 | println("stop")
188 | }
189 |
190 | /**
191 | * 提取函数重构
192 | */
193 | private suspend fun doWorld(world : String){
194 | delay(1000)
195 | println(world)
196 | }
197 |
198 | }
199 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/NullAndNullCheckDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin可空类型、与空安全 详解
5 | * author : Jetictors
6 | * time : 2018/1/14 15:47
7 | * version : v1.0.1
8 | */
9 |
10 | class NullAndNullCheckDemo {
11 |
12 | private fun operatorEvils3() {
13 |
14 | // 正常转换
15 | val a = 10
16 | val num3 : Int? = a as? Int
17 | // null
18 | val num4 : Int? = "123" as? Int
19 |
20 | println("nun3 = $num3 \t num4 = $num4")
21 | }
22 |
23 | /**
24 | * !! 操作符用法
25 | */
26 | private fun operatorEvils2() {
27 | val testStr : String? = null
28 |
29 | println(testStr!!.length)
30 | }
31 |
32 | /**
33 | * ?: 操作符用法
34 | */
35 | private fun operatorEvils1() {
36 | val testStr : String? = null
37 |
38 | var length = 0
39 |
40 | // 例: 当testStr不为空时,输出其长度,反之输出-1
41 |
42 | // 传统写法
43 | length = if (testStr != null) testStr.length else -1
44 |
45 | // ?: 写法
46 | length = testStr?.length ?: -1
47 |
48 | println(length)
49 | }
50 |
51 | /**
52 | * let{ } 函数的用法
53 | */
54 | private fun operatorLet() {
55 | // let函数是一个高阶函数
56 |
57 | // 例: 排除掉数组中的空元素
58 | val arrTest : Array = arrayOf(1,2,null,3,null,5,6,null)
59 |
60 | // 传统写法
61 | for (index in arrTest) {
62 | if (index == null){
63 | continue
64 | }
65 | println("index => $index")
66 | }
67 |
68 | // let写法
69 | for (index in arrTest) {
70 | index?.let { println("index => $it") }
71 | }
72 |
73 | }
74 |
75 | /**
76 | * 测试使用符号 ?. 链式调用方法
77 | */
78 | private fun testBuilder() {
79 | val builder1 : Test.Builder? = Test.Builder().setName("Lily")?.setSex("女")?.setAge(10)
80 | val builder2 : Test.Builder? = Test.Builder().setName("Tom")?.setSex(null)?.setAge(10)
81 | println(builder1.toString())
82 | println(builder2.toString())
83 |
84 | val testStr : String? = null
85 | val result = testStr?.length?.plus(5)?.minus(10)
86 | println(result)
87 | }
88 |
89 | /**
90 | * 当函数有返回值的情况下使用可空类型,其方法的返回值类型同样要加上?符号
91 | */
92 | private fun funNullMethod() : Int? {
93 | val str : String? = "123456"
94 | return str?.let { str.length }
95 | }
96 |
97 | /**
98 | * 判断可空类型的两种方式
99 | */
100 | private fun funNullCheck() {
101 |
102 | var str : String? = "123456"
103 | str = null
104 |
105 | // 1. if...else...判断
106 |
107 | if (str == null){
108 | println("变量str为空")
109 | }else{
110 | println("str.length => $str.length")
111 | }
112 |
113 | // 2. 使用符号`?.`判断 , 可以方便的调用变量的属性、方法等
114 | println(str?.length) // 当变量str为null时,会返回空(null)
115 |
116 | }
117 |
118 | private fun funNull() {
119 |
120 | // 定义一个不可为空的变量,用var修饰的变量可以被重新赋值,用val修饰的变量则不能,但是不能赋值为null
121 | var a : Int = 12
122 | val b : Int = 13
123 |
124 | a = 20
125 | // a = null 不能复制为null
126 | // b = 20 不能被重新赋值
127 |
128 | if(a == null){
129 | // 这样的判断毫无意义,因为变量a永远不可能null
130 | }
131 |
132 | /*
133 | 定义可空类型的变量,即变量可以被赋值为null
134 | 定义格式为:修饰符 变量名 : 类型? = 值
135 | */
136 | val nullA : Int? = null
137 | val nullB : Int? = 13
138 |
139 | if(nullA == null){
140 | println("nullA = $nullA")
141 | }
142 | }
143 |
144 | class Test{
145 |
146 | class Builder{
147 | private var name : String? = "Tom"
148 | private var age : Int? = 0
149 | private var sex : String? = "男"
150 |
151 | fun setName(name : String) : Builder?{
152 | this.name = name
153 | return this
154 | }
155 |
156 | fun setAge(age : Int) : Builder?{
157 | this.age = age
158 | return this
159 | }
160 |
161 | fun setSex(sex: String?) : Builder?{
162 | this.sex = sex
163 | return this
164 | }
165 |
166 | override fun toString(): String {
167 | return "Builder(name=$name, age=$age, sex=$sex)"
168 | }
169 | }
170 | }
171 |
172 | fun test(){
173 | funNull()
174 | funNullCheck()
175 | println(funNullMethod())
176 | testBuilder()
177 | operatorLet()
178 | operatorEvils1()
179 | operatorEvils2()
180 | operatorEvils3()
181 | }
182 | }
183 |
184 |
185 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/function/SeniorFunctionDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.function
2 |
3 | /**
4 | * 描述 : 高阶函数详解
5 | * author : Jetictors
6 | * time : 2018/4/7 22:25
7 | * version : v1.0.1
8 | */
9 |
10 |
11 | class SeniorFunctionDemo{
12 |
13 | /**
14 | * 测试T.let()函数,以及查看其和T.also()和`T.apply()`函数的区别
15 | */
16 | private fun testLet() {
17 | "kotlin".let {
18 | println("原字符串:$it") // kotlin
19 | it.reversed()
20 | }.let {
21 | println("反转字符串后的值:$it") // niltok
22 | it.plus("-java")
23 | }.let {
24 | println("新的字符串:$it") // niltok-java
25 | }
26 |
27 | "kotlin".also {
28 | println("原字符串:$it") // kotlin
29 | it.reversed()
30 | }.also {
31 | println("反转字符串后的值:$it") // kotlin
32 | it.plus("-java")
33 | }.also {
34 | println("新的字符串:$it") // kotlin
35 | }
36 |
37 | "kotlin".apply {
38 | println("原字符串:$this") // kotlin
39 | this.reversed()
40 | }.apply {
41 | println("反转字符串后的值:$this") // kotlin
42 | this.plus("-java")
43 | }.apply {
44 | println("新的字符串:$this") // kotlin
45 | }
46 | }
47 |
48 | /**
49 | * 测试T.also()函数,并说明和T.apply()的区别
50 | */
51 | private fun testAlso() {
52 |
53 | "kotlin".also {
54 | println("结果:${it.plus("-java")}")
55 | }.also {
56 | println("结果:${it.plus("-php")}")
57 | }
58 |
59 | "kotlin".apply {
60 | println("结果:${this.plus("-java")}")
61 | }.apply {
62 | println("结果:${this.plus("-php")}")
63 | }
64 |
65 | }
66 |
67 | /**
68 | * 测试T.takeUnless()函数
69 | */
70 | private fun testTakeUnless() {
71 |
72 | val str = "kotlin"
73 |
74 | val result = str.takeUnless {
75 | it.startsWith("ko")
76 | }
77 |
78 | println("result = $result")
79 | }
80 |
81 | /**
82 | * 测试T.takeIf()函数
83 | */
84 | private fun testTakeIf() {
85 |
86 | val str = "kotlin"
87 |
88 | val result = str.takeIf {
89 | it.startsWith("ko")
90 | }
91 |
92 | println("result = $result")
93 | }
94 |
95 | /**
96 | * 测试repeat()高阶函数
97 | */
98 | private fun testRepeat() {
99 | repeat(5){
100 | println("我是重复的第${it + 1}次,我的索引为:$it")
101 | }
102 | }
103 |
104 | /**
105 | * 测试自定义的高阶函数
106 | */
107 | private fun testDemo() {
108 | val result1 = resultByOpt(1,2){
109 | num1, num2 -> num1 + num2
110 | }
111 |
112 | val result2 = resultByOpt(3,4){
113 | num1, num2 -> num1 - num2
114 | }
115 |
116 | val result3 = resultByOpt(5,6){
117 | num1, num2 -> num1 * num2
118 | }
119 |
120 | val result4 = resultByOpt(6,3){
121 | num1, num2 -> num1 / num2
122 | }
123 |
124 | println("result1 = $result1")
125 | println("result2 = $result2")
126 | println("result3 = $result3")
127 | println("result4 = $result4")
128 | }
129 |
130 | private fun resultByOpt(num1 : Int , num2 : Int , result : (Int ,Int) -> Int) : Int{
131 | return result(num1,num2)
132 | }
133 |
134 | private fun testLock() {
135 | val testStr = "abc"
136 | val sum = testStr.sumBy { it.toInt() }
137 | println(sum)
138 |
139 | }
140 |
141 | /**
142 | * 测试with(参数){}函数
143 | */
144 | private fun testWith() {
145 | val str = "kotlin"
146 | with(str) {
147 | println( "length = ${this.length}" )
148 | println( "first = ${first()}")
149 | println( "last = ${last()}" )
150 | }
151 |
152 | val newStr : String? = "kotlin"
153 |
154 | with(newStr){
155 | println( "length = ${this?.length}" )
156 | println( "first = ${this?.first()}")
157 | println( "last = ${this?.last()}" )
158 | }
159 |
160 | newStr?.run {
161 | println( "length = $length" )
162 | println( "first = ${first()}")
163 | println( "last = ${last()}" )
164 | }
165 | }
166 |
167 | /**
168 | * 测试T.run{}函数
169 | */
170 | private fun testRun2() {
171 | val str = "kotlin"
172 | str.run {
173 | println( "length = ${this.length}" )
174 | println( "first = ${first()}")
175 | println( "last = ${last()}" )
176 | }
177 | }
178 |
179 | /**
180 | * 测试run{}函数
181 | */
182 | private fun testRun1() {
183 | val str = "kotlin"
184 |
185 | run{
186 | val str = "java"
187 | println("str = $str")
188 | }
189 |
190 | println("str = $str")
191 |
192 | val index = 3
193 | val num = run {
194 | when(index){
195 | 0 -> "kotlin"
196 | 1 -> "java"
197 | 2 -> "php"
198 | 3 -> "javaScript"
199 | else -> "none"
200 | }
201 | }.length
202 | println("num = $num")
203 |
204 | }
205 |
206 | /**
207 | * 测试TODO函数
208 | */
209 | private fun testTODO() {
210 | TODO("测试TODO函数,是否显示抛出错误")
211 | }
212 |
213 | fun test(){
214 | testLock()
215 | testDemo()
216 | testTODO()
217 | testRun1()
218 | testRun2()
219 | testWith()
220 | testAlso()
221 | testLet()
222 | testTakeIf()
223 | testTakeUnless()
224 | testRepeat()
225 | }
226 |
227 | }
228 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # KotlinLearn
3 |
4 | 这是一个关于`Kotlin`教程的项目,学好`Koltin`从这里开始,当你看完这个系列的所有文章时,我相信你是绝对有收获的。
5 |
6 |
7 |
8 | 
9 |
10 |
11 |
12 | ## 写这个系列教程的初衷
13 |
14 | 本人作为一个`Android`开发者,在`Kotlin`语言正式出现在人们面前的时候,或多或少的接触到了这门语言,并
15 | 自学了一部分,当`Google`宣布`Kotlin`成为`Android`开发的标准语言时,才有打算用心的去学习这门语言,并能用于实际的开
16 | 发当中。在我学习的过程中,学的越深入越被`Kotlin`的简洁以及良好的阅读性深深的折服。但是在官方的文档中,写
17 | 的实列不是很详细,有些代码甚至看不懂其实现,基础性的东西几乎不存在。如果你没有一定的编程经验我相信你也是看不懂的。
18 |
19 | 但是请你不要放弃对这门语言的学习,我也是一点一点学习过来的,你在学习过程中遇到的坑,可能我也遇到过。我非常欢迎各位
20 | 一起学习、一起探索。让我们共同进步。
21 |
22 | 所以,我会根据自身的编程经验去写完整个`Kotlin`系列文章。整个教程由浅入深,即使你没有编程经验你也能看懂,教程中会
23 | 介绍`Koltin`的特性,以及其和`Java`的差异性。让更多的朋友爱上这门语言。
24 |
25 | ## 开撸
26 | 话不多说,让我们忘记生活的烦恼、放下沉重的枷锁、沉浸在代码的世界中,放大音乐分贝,迈开脚步开始学习`Kotlin`大法吧。
27 |
28 | ## 学习架构
29 | 我把这个教程命名为:从无到有系列,这个系列目前还没写完,故而下面的链接有一些是没有实际内容的,我会在后面持续的补齐,这里只是实现了整个教程的大纲。
30 |
31 | 整个项目根据学习的难以程度以及学习路线我分为了五个模块。我会按照的学习架构去排序。大家可以按照这个顺序去学习...
32 |
33 | #### 引言
34 | - [1、 17 位谷歌 Android 开发专家是如何看待 Kotlin 的?](https://mp.weixin.qq.com/s/mWPJiefaNpK8EuoJYvhbhg)
35 | - [2、 用 Kotlin 开发 Android 项目是一种什么样的感受?(一)](https://www.jianshu.com/p/8a1fce6fa93a)
36 | - [3、 用 Kotlin 开发 Android 项目是一种什么样的感受?(二)](https://www.jianshu.com/p/b444aea1b038)
37 |
38 | #### 初级篇
39 | > 对于入门篇的内容不多,主要是讲解了`Kotlin`中的基础语法,涵盖了`开发环境搭建`、`变量`、`常量`、`注释`、`数据类型`、`控制语句`,`操作符重载`、`空安全`、`基本函数`、`字符串处理`等
40 |
41 | - [1、 开发环境搭建](https://juejin.im/post/5a37e2dbf265da43231b1504)
42 | - [2、 变量、常量、注释](https://juejin.im/post/5a39ef7af265da4311205967)
43 | - [3、 数据类型](https://juejin.im/post/5a36020b6fb9a0451543f5c8)
44 | - [4、 逻辑控制语句](https://juejin.im/post/5a369ccaf265da4325296247)
45 | - [5.1、 一元、二元操作符](https://juejin.im/post/5a4ce9865188257d6a7ef291)
46 | - [5.2、 比较、区间、未运算操作符(未完成)](#)
47 | - [6、 可空类型、空安全、类型转换](https://juejin.im/post/5a5b06f26fb9a01cb42c5206)
48 | - [7、 基础函数使用](https://juejin.im/post/5a6377425188257329148665)
49 | - [8、 字符串的常用操作总结](https://juejin.im/post/5b0ae06df265da0db64e3d63)
50 |
51 | #### 中级篇
52 | > `Kotlin`是一门`面向对象`的开发语言。既然是面向对象,则在中级篇主要讲解其`三大特性`,以及`类成员`、`数据类`、`抽象类`、`接口类`、`内部类`、`继承类`等关于`Kotlin`面向对象的方方面面的讲解
53 |
54 | - [1、 类的声明与使用](https://juejin.im/post/5a3297de6fb9a045055e295e)
55 | - [2、 属性与字段](https://juejin.im/post/5a6378266fb9a01ca10b00e4)
56 | - [3、 可见性修饰符](https://juejin.im/post/5a3293ec51882531926ebfe6)
57 | - [4、 继承类](https://juejin.im/post/5a6303fb51882573467d0fbc)
58 | - [5、 接口类、枚举类](https://juejin.im/post/5a34c551518825552b3f9c91)
59 | - [6、 数据类、密封类](https://juejin.im/post/5a37e4b45188253aea1f7219)
60 | - [7、 抽象类、内部类、嵌套类](https://juejin.im/post/5a48a0e8518825455f2fa070)
61 | - [8、 类型别名与属性名冲突解决](https://juejin.im/post/5c8cbd45f265da2dda6997d3)
62 | - [9、 解构声明(未完成)](#)
63 | - [10、伴生对象与对象声明(未完成)](#)
64 |
65 | #### 高级篇
66 | > 高级篇的内容要多一些,只要是对`Kotlin`中的高级用法以及一些独特的东西。涵盖了`lambda表达式`、`高阶函数`、`集合`、`泛型`、`扩展`、`委托`、`异常处理`、`注解`、`反射`、`协程`等
67 |
68 | - [1、 Lambda表达式](https://juejin.im/post/5ab9a5ccf265da239f076284)
69 | - [2、 高阶函数](https://juejin.im/post/5b198c675188257d7a49b3ec)
70 | - [3、 内联函数(未完成)](#)
71 | - [4.1、 集合的使用](https://juejin.im/post/5ab7a9c4f265da2377196038)
72 | - [4.2、 集合的常用操作符总结](https://juejin.im/post/5b1f7699f265da6e155d5965)
73 | - [5、 泛型(未完成)](#)
74 | - [6、 扩展(未完成)](#)
75 | - [7、异常处理(未完成)](#)
76 | - [8、 委托(未完成)](#)
77 | - [9、 注解(未完成)](#)
78 | - [10、 反射(未完成)](#)
79 | - [11、 协程(未完成)](https://github.com/Kotlin/kotlinx.coroutines)
80 |
81 | #### 进阶篇
82 | > 进阶篇主要讲解的是在实际开发项目中的注意事项及一些高级操作,例如`Kotlin`中的`设计模式`、`编码规范`等
83 |
84 | - [1、 约定俗成的编码规范(未完成)](#)
85 | - [2、 单列模式(未完成)](#)
86 | - [3、 工厂方法模式(未完成)](#)
87 | - [4、 抽象工厂模式(未完成)](#)
88 | - [5、 建造者模式(未完成)](#)
89 | - [6、 原型模式(未完成)](#)
90 | - [7、 适配器模式(未完成)](#)
91 | - [8、 桥接模式(未完成)](#)
92 | - [9、 组合模式(未完成)](#)
93 | - [10、 装饰模式(未完成)](#)
94 | - [11、 外观模式(未完成)](#)
95 | - [12、 享元模式(未完成)](#)
96 | - [13、 代理模式(未完成)](#)
97 | - [14、 职责链模式(未完成)](#)
98 | - [15、 命令模式(未完成)](#)
99 | - [16、 解释器模式(未完成)](#)
100 | - [17、 迭代器模式(未完成)](#)
101 | - [18、 中介者模式(未完成)](#)
102 | - [19、 备忘录模式(未完成)](#)
103 | - [20、 观察者模式(未完成)](#)
104 | - [21、 状态模式(未完成)](#)
105 | - [22、 策略模式(未完成)](#)
106 | - [23、 模版方法模式(未完成)](#)
107 | - [24、 访问者模式(未完成)](#)
108 |
109 | #### 实战篇
110 | > 实战篇主要向大家介绍使用`Kotlin`开发`Android`项目时,介绍一些常用和`Kotlin`一起开发的库,以及对他们的使用及讲解。
111 | 比如说`Anko`、`Dagger2`、`RxKotlin`、或者用`Kotlin`编写的一些自定义组件等等...
112 |
113 | - [1、 使用Anko,让你告别xml布局](https://github.com/Jetictors/anko_kotlin_gank_client)
114 | - [2、 Kotlin中使用Dagger2的坑](https://github.com/Jetictors/kotlin-java-dagger2)
115 | - [3、 RxKotlin总结(未完成)](#)
116 | - [4、 使用Koltin编写一个竖行显示的TextView(未完成)](#)
117 |
118 | ## 其他
119 |
120 | 在这里我意思整合了一些关于`Kotlin`的学习资源,以供大家学习。
121 |
122 | #### 官网
123 | - [Kotlin官网文档](https://kotlinlang.org/docs/reference/)
124 | - [kotlin中文官网文档](http://www.kotlincn.net/docs/reference/)
125 | - [Kotlin在线IDE](https://try.kotlinlang.org/)
126 | - [Kotlin On Github](https://github.com/JetBrains/kotlin)
127 |
128 | #### 视频教程
129 | - [Kotlin系列视频教程](https://github.com/enbandari/Kotlin-Tutorials)
130 |
131 | #### 书籍
132 | 关于书籍的分享,这里有着官网的中英文`PDF`文档,`Kotlin`极简教程、`Kotlin`程序开发入门经验等等书籍。这些我都分享在了我的`Kotlin`交流群里面。这里就不一一的分享了。
133 |
134 | #### 更多
135 | - [Kotlin相关经验文章](https://juejin.im/tag/Kotlin?utm_source=awesome_kotlin&utm_medium=jjzl)
136 |
137 | #### 开源项目
138 | - [GankClient-Kotlin](https://github.com/githubwing/GankClient-Kotlin) —— 用`Koltin`编写的`Gank`客户端
139 | - [PoiShuhui-Kotlin](https://github.com/wuapnjie/PoiShuhui-Kotlin) —— 用`Kotlin`写的简单漫画APP
140 | - [KotlinMvp](https://github.com/git-xuhao/KotlinMvp) —— 基于`Kotlin+MVP+Retrofit+RxJava+Glide`等架构实现短视频类APP练手项目,UI简约,详细注释
141 | - [Eyepetizer-in-Kotlin](https://github.com/LRH1993/Eyepetizer-in-Kotlin) —— 用`Kotlin`撸一款`Eyepetizer`
142 |
143 | ## 最后
144 | 我相信在你学完整个系列教程之后,一定是可以用`Kotlin`进行实际项目开发的。近期我也会用`Koltin`语言去编写我自己的`Android`项目,也会用`Kotlin`去实现后端用于我`APP`中的接口提供。
145 | 如果你在学习过程中遇到任何的问题,不管你是写`后端`、`Android`以及`前端`的开发者都可以联系我,或者对于`Android`开发很有兴趣。都可以在项目`Issuse`我,或者加入在下的`Koltin`交流群一起学习、研究。
146 |
147 |
148 |
欢迎各位大佬进群共同研究、探索
149 |
150 | QQ群号:497071402
151 |
152 |
153 | 
154 |
155 |
156 |
157 |
158 |
159 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/OperatorStringDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | import java.util.regex.Pattern
4 |
5 | /**
6 | * 描述 : 字符串的常用操作
7 | * author : Jetictors
8 | * time : 2018/5/28 0:52
9 | * version : v1.0.1
10 | */
11 |
12 | class OperatorStringDemo {
13 |
14 | /**
15 | * 字符串替换
16 | */
17 | private fun replaceStr() {
18 | val str = "Kotlin is a very good programming language"
19 |
20 | // oldChar: 要替换的字符,newChar: 替换的字符
21 | println("----------- 1、replace() ------------")
22 | println(str.replace('a','A',true))
23 |
24 | println("----------- 2、replace() ------------")
25 | // oldValue: 要替换的字符串, newValue: 替换的字符串
26 | println(str.replace("Kotlin","Java"))
27 |
28 | println("----------- 3、replace() ------------")
29 | /*
30 | 利用正则表达式替换
31 | regex: 规则
32 | replacement : 替换的字符
33 |
34 | */
35 | val str2 = "1234a kotlin 5678 3 is 4"
36 | println(str2.replace(Regex("[0-9]+"),"kotlin"))
37 |
38 | println("----------- 4、replace() ------------")
39 | /*
40 | 根据定义的正则规则去匹配源字符串,把满足规则的字符串通过`transform{}`高阶函数映射的新字符串替换。
41 | regex: 规则
42 | transform : 高阶函数
43 | */
44 | val newS = str2.replace(Regex("[0-9]")) { "abcd " }
45 | println(newS)
46 |
47 | // replaceFirst
48 | println("----------- replaceFirst() ------------")
49 | println(str.replaceFirst('a','A'))
50 | println(str.replaceFirst( "Kotlin","Java"))
51 |
52 |
53 | // replaceBefore
54 | println("----------- replaceBefore() ------------")
55 | println(str.replaceBefore('a',"AA"))
56 | println(str.replaceBefore("Kotlin","Java"))
57 |
58 | // replaceBeforeLast
59 | println("----------- replaceBeforeLast() ------------")
60 | println(str.replaceBeforeLast('a',"AA"))
61 | println(str.replaceBeforeLast("Kotlin","Java"))
62 |
63 | // replaceAfter
64 | println("----------- replaceAfter() ------------")
65 | println(str.replaceAfter('a',"AA"))
66 | println(str.replaceAfter("Kotlin","Java"))
67 |
68 | // replaceAfterLast
69 | println("----------- replaceAfterLast() ------------")
70 | println(str.replaceAfterLast('a',"AA"))
71 | println(str.replaceAfterLast("Kotlin","Java"))
72 | }
73 |
74 | /**
75 | * 字符串分割
76 | */
77 | private fun spiltStr() {
78 | val str1 = "Kotlin is a very good programming language"
79 |
80 | val list1 = str1.split(' ')
81 | for (str in list1){
82 | print("$str \t")
83 | }
84 |
85 | println()
86 |
87 | val list2 = str1.split(" ")
88 | for (str in list2){
89 | print("$str \t")
90 | }
91 |
92 | println()
93 |
94 | val str2 = "1 kotlin 2 java 3 Lua 4 JavaScript"
95 | val list3 = str2.split(Regex("[0-9]+"))
96 | for (str in list3){
97 | print("$str \t")
98 | }
99 |
100 | println()
101 |
102 | val list4 = str2.split(Pattern.compile("[0-9]+"))
103 | for (str in list4){
104 | print("$str \t")
105 | }
106 |
107 | println()
108 |
109 | val str3 = "a b c d e f g h 2+3+4+5"
110 | val list5 = str3.split(' ','+')
111 | for (str in list5){
112 | print("$str \t")
113 | }
114 | }
115 |
116 | /**
117 | * 字符串截取
118 | */
119 | private fun subStr() {
120 | val str = "Kotlin is a very good programming language"
121 |
122 | println(str.substring(10))
123 | println(str.substring(0,15))
124 | println(str.substring(IntRange(0,15)))
125 |
126 | println(str.subSequence(0,15))
127 | println(str.subSequence(IntRange(0,15)))
128 | }
129 |
130 | private fun optStr() {
131 |
132 | // 字符串链接
133 | val oldStr = "kotlin"
134 | println(oldStr.plus(" very good"))
135 | println(oldStr + " very good")
136 |
137 | // 字符串反转
138 | val str = "kotlin"
139 | println("字符串反转:${str.reversed()}")
140 |
141 | // 检测字符串的起始字符与结尾字符
142 | println(str.endsWith("lin"))
143 | println(str.endsWith('n'))
144 |
145 | println(str.startsWith('k'))
146 | println(str.startsWith("kot"))
147 | println(str.startsWith("lin",3))
148 | }
149 |
150 | /**
151 | * 字符串查找
152 | */
153 | private fun findStr(){
154 |
155 | val str = "kotlin very good"
156 |
157 | println(str.first())
158 | println(str.first { it == 't' })
159 | println(str.firstOrNull())
160 | println(str.firstOrNull{it == 't'})
161 | println(str.last())
162 | println(str.last { it == 'o' })
163 | println(str.lastOrNull())
164 | println(str.lastOrNull { it == 'o' })
165 |
166 | println(str.indexOfFirst { it == 'o' })
167 | println(str.indexOfLast { it == 'o' })
168 | println(str.indexOf('o',0))
169 | println(str.indexOf("very",0))
170 | println(str.lastIndexOf('o'))
171 | println(str.lastIndexOf("good"))
172 | }
173 |
174 | /**
175 | * 统计
176 | */
177 | private fun getStrLength(){
178 |
179 | val str = "kotlin very good"
180 |
181 | // 1. 直接用length属性获取
182 | println("str.length => ${str.length}")
183 |
184 | // 2. 用count()函数获取
185 | println("str.count() => ${str.count()}")
186 |
187 | // 3. 统计重复
188 | val count = str.count { it == 'o' }
189 | println("count : $count")
190 | }
191 |
192 |
193 | /**
194 | * 检测字符串是否为空,或空字符串,以及是否包含了空格
195 | */
196 | private fun checkNullStr(){
197 |
198 | val str : String? = "kotlin"
199 |
200 | println(str?.isEmpty())
201 | println(str?.isNotEmpty())
202 | println(str.isNullOrEmpty())
203 | println(str?.isBlank())
204 | println(str?.isNotBlank())
205 | println(str.isNullOrBlank())
206 |
207 | }
208 |
209 | fun test(){
210 | checkNullStr()
211 | getStrLength()
212 | optStr()
213 | findStr()
214 | subStr()
215 | spiltStr()
216 | replaceStr()
217 | }
218 |
219 | }
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/OperatorDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : 操作符重载详解
5 | * author : Jetictors
6 | * time : 2018/1/3 23:21
7 | * version : v1.0.1
8 | */
9 |
10 | class OperatorDemo {
11 |
12 | fun test(){
13 | unitaryOperator()
14 | unitaryCommonOperator()
15 | binaryOperator()
16 | compareOperator()
17 | testRangTo()
18 | testIn()
19 | testIs()
20 | }
21 |
22 | /**
23 | * 类型判断
24 | */
25 | private fun testIs() {
26 | val a = 0
27 | }
28 |
29 | /**
30 | * 包含操作符 in
31 | */
32 | private fun testIn() {
33 | val str = "kotlin"
34 | val result1 = "o" in str
35 | val result2 = str.contains("o")
36 | println("$result1 \t $result2")
37 | }
38 |
39 |
40 | /**
41 | * 区间操作符
42 | */
43 | private fun testRangTo() {
44 |
45 | /*
46 | 操作符为(..),其有两个操作数,且都是整型
47 | */
48 | val a = 1
49 | val b = 5
50 |
51 | // 操作符实现
52 | val s = 3 in a .. b // true,因为3在区间[1,5]之内
53 | println("s = $s")
54 | for (index in a .. b){
55 | print("index = $index \t")
56 | }
57 |
58 | println()
59 |
60 | // 操作符重载方式实现
61 | val t = 3 in a.rangeTo(b)
62 | println("t = $t")
63 | for (index in a.rangeTo(b)){
64 | print("index = $index \t")
65 | }
66 | println()
67 | }
68 |
69 | /**
70 | * 比较运算符
71 | */
72 | private fun compareOperator() {
73 | /*
74 | > 、< 、>= 、<=
75 | */
76 | val a = 12
77 | val b = 5
78 |
79 | // 操作符实现
80 | println("a > b = ${a > b}")
81 | println("a < b = ${a < b}")
82 | println("a >= b = ${a >= b}")
83 | println("a <= b = ${a <= b}")
84 |
85 | // 操作符重载方式实现
86 | println("a.compareTo(b) > 0 = ${a.compareTo(b) > 0}")
87 | println("a.compareTo(b) < 0 = ${a.compareTo(b) < 0}")
88 | println("a.compareTo(b) >= 0 = ${a.compareTo(b) >= 0}")
89 | println("a.compareTo(b) <= 0 = ${a.compareTo(b) <= 0}")
90 | }
91 |
92 | /**
93 | * 二元操作
94 | */
95 | private fun binaryOperator() {
96 | basicBinaryOperator()
97 | commonBinaryOperator()
98 | seniorBinaryOperator()
99 | }
100 |
101 | /**
102 | * 对一个集合使用plus()和plusAssign()
103 | */
104 | private fun seniorBinaryOperator() {
105 | var arrA = arrayListOf("1","2","3","4")
106 | var arrB = arrayListOf("1","2","3","4")
107 |
108 | arrA.plusAssign(arrB)
109 |
110 | for (a in arrA){
111 | print("$a \t")
112 | }
113 | }
114 |
115 | /**
116 | * 复合的二元操作
117 | */
118 | private fun commonBinaryOperator() {
119 | var a = 10
120 | var b = 2
121 | var c = "Kotlin"
122 |
123 | // 主要演示字符串的+=
124 | c += a
125 | print("c = $c \t" )
126 |
127 | a += b
128 | print("a = $a \t")
129 |
130 | a = 10
131 | a -= b
132 | print("a = $a \t")
133 |
134 | a = 10
135 | a *= b
136 | print("a = $a \t")
137 |
138 | a = 10
139 | a /= b
140 | print("a = $a \t")
141 |
142 | a = 10
143 | a %= b
144 | println("a = $a \t")
145 |
146 | // 操作符重载方式实现
147 | a = 10
148 | c = "Kotlin"
149 | c = c.plus(a)
150 | print("c = $c \t")
151 |
152 | a = 10
153 | a = a.plus(b)
154 | print("a = $a \t")
155 |
156 | a = 10
157 | a = a.minus(b)
158 | print("a = $a \t")
159 |
160 | a = 10
161 | a = a.times(b)
162 | print("a = $a \t")
163 |
164 | a = 10
165 | a = a.div(b)
166 | print("a = $a \t")
167 |
168 | a = 10
169 | a = a.rem(b)
170 | println("a = $a \t")
171 | }
172 |
173 | /**
174 | * 简单的二元操作
175 | */
176 | private fun basicBinaryOperator(){
177 | val a = 10
178 | val b = 2
179 | val c = "2"
180 | val d = "Kotlin"
181 |
182 | // 操作符实现
183 | println("a + d = " + a + d)
184 | println("c + d = " + c + d)
185 | println("a + b = ${a + b} \t a - b = ${a - b} \t a * b = ${a * b} \t a / b = ${a / b} \t a % b = ${a % b}")
186 |
187 | // 操作符重载实现
188 | println("a + b = ${a.plus(b)} \t a - b = ${a.minus(b)} \t a * b = ${a.times(b)} \t a / b = ${a.div(b)} \t " +
189 | "a % b = ${a.rem(b)} \t a .. d = ${a.rangeTo(b)}")
190 | // println(a.plus(d)) 错误:因为第一个操作数`a`限制了其plus()方法的参数,
191 | // println(d.plus(a)) 正确:因为plus()方法的参数为超(Any)类型
192 | }
193 |
194 | /**
195 | * 一元操作
196 | */
197 | private fun unitaryOperator() {
198 |
199 | /*
200 | 简单的一元操作:有三种一元操作
201 | 1. `+` 表示正数的意思,其操作数为数值型
202 | 2. `-` 表示负数的意思,其操作数为数值型
203 | 3. `!` 表示取反的意思,其操作数为boolean类型
204 | */
205 |
206 | var a = 1
207 | var b = -2
208 | var c = true
209 | var d = false
210 |
211 | // 操作符实现
212 | println("+a = ${+a}\t -a = ${-a}\t !c = ${!c}")
213 | println("+b = ${+b}\t -b = ${-b}\t !d = ${!d}")
214 |
215 | // 操作符重载方式实现
216 | println("+a = ${a.unaryPlus()}\t -a = ${a.unaryMinus()}\t !c = ${c.not()}")
217 | println("+b = ${b.unaryPlus()}\t -b = ${b.unaryMinus()}\t !d = ${d.not()}")
218 | }
219 |
220 | /**
221 | * 复杂的一元元操作
222 | */
223 | private fun unitaryCommonOperator() {
224 | /*
225 | 复杂的一元操作:有4种一元操作
226 | 1. `a++` :后缀自增
227 | 2. `a--` : 后缀自减
228 | 1. `++a` :前缀自增
229 | 2. `--a` : 前缀自减
230 | */
231 | var a = 10
232 | var b = 10
233 | var c = 10
234 | var d = 10
235 |
236 | // Java实现
237 | println("a++ = ${a++} \t b-- = ${b--} \t ++c = ${++c} \t --d = ${--d}")
238 |
239 | a = 10
240 | b = 10
241 | c = 10
242 | d = 10
243 |
244 | // 操作符重载方式实现
245 | a.also { a.inc() }
246 | b.also { b.dec() }
247 | c.inc().also { c = it }
248 | d.dec().also { d = it }
249 | println("a = $a \t b = $b \t c = $c \t d = $d")
250 |
251 | }
252 |
253 | }
254 |
255 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/other/OperaCollectionDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.other
2 |
3 | /**
4 | * 描述 : 处理集合的高级函数
5 | * author : Jetictors
6 | * time : 2018/4/1 22:59
7 | * version : v1.0.1
8 | */
9 |
10 | class OperaCollectionDemo{
11 |
12 |
13 | /**
14 | * 生产操作符
15 | */
16 | private fun optProduce() {
17 | val list1 = listOf(1,2,3,4)
18 | val list2 = listOf("kotlin","Android","Java","PHP","JavaScript")
19 |
20 | // plus() 和 `+`一样
21 | println(list1.plus(list2))
22 | println(list1 + list2)
23 |
24 | // zip
25 | println(list1.zip(list2))
26 | println(list1.zip(list2){ // 组成的新集合由元素少的原集合决定
27 | it1,it2-> it1.toString().plus("-").plus(it2)
28 | })
29 |
30 | // unzip
31 | val newList = listOf(Pair(1,"Kotlin"),Pair(2,"Android"),Pair(3,"Java"),Pair(4,"PHP"))
32 | println(newList.unzip())
33 |
34 | // partition
35 | println(list2.partition { it.startsWith("Ja") })
36 | }
37 |
38 | /**
39 | * 过滤操作符
40 | */
41 | private fun optFilter() {
42 |
43 | val list1 = listOf(-1,-3,1,3,5,6,7,2,4,10,9,8)
44 | val list2 = listOf(1,3,4,5,null,6,null,10)
45 | val list3 = listOf(1,1,5,2,2,6,3,3,7,4,4,8)
46 |
47 | println(" ------ filter -------")
48 | println(list1.filter { it > 1 })
49 | println(list1.filterIndexed { index, result ->
50 | index < 5 && result > 3
51 | })
52 | println(list1.filterNot { it > 1 })
53 | println(list2.filterNotNull())
54 |
55 | println(" ------ take -------")
56 | println(list1.take(5))
57 | println(list1.takeWhile { it < 5 })
58 | println(list1.takeLast(5))
59 | println(list1.takeLastWhile { it > 5 })
60 |
61 | println(" ------ drop -------")
62 | println(list1.drop(5))
63 | println(list1.dropWhile { it < 5 })
64 | println(list1.dropLast(5))
65 | println(list1.dropLastWhile { it > 5 })
66 |
67 | println(" ------ distinct -------")
68 | println(list3.distinct())
69 | println(list3.distinctBy { it + 2 })
70 |
71 | println(" ------ slice -------")
72 | println(list1.slice(listOf(1,3,5,7)))
73 | println(list1.slice(IntRange(1,5)))
74 |
75 | }
76 |
77 | /**
78 | * 映射操作符
79 | */
80 | private fun optMapped() {
81 | val list1 = listOf("kotlin","Android","Java","PHP","JavaScript")
82 |
83 | println(list1.map { "str-".plus(it) })
84 |
85 | println(list1.mapNotNull { "str-".plus(it) })
86 |
87 | println(list1.mapIndexed { index, str ->
88 | index.toString().plus("-").plus(str)
89 | })
90 |
91 | println(list1.mapIndexedNotNull { index, str ->
92 | index.toString().plus("-").plus(str)
93 | })
94 |
95 | println( list1.flatMap { listOf(it,"new-".plus(it)) })
96 |
97 | println(list1.groupBy { if (it.startsWith("Java")) "big" else "latter" })
98 |
99 | }
100 |
101 | /**
102 | * 顺序操作符
103 | */
104 | private fun optSort() {
105 | val list1 = listOf(-1,-3,1,3,5,6,7,2,4,10,9,8)
106 |
107 | // 反序
108 | println(list1.reversed())
109 |
110 | // 升序
111 | println(list1.sorted())
112 |
113 | // 根据条件升序,即把不满足条件的放在前面,满足条件的放在后面
114 | println(list1.sortedBy { it % 2 == 0})
115 |
116 | // 降序
117 | println(list1.sortedDescending())
118 |
119 | // 根据条件降序,和`sortedBy{}`相反
120 | println(list1.sortedByDescending { it % 2 == 0 })
121 |
122 | }
123 |
124 | /**
125 | * 统计操作符
126 | */
127 | private fun optCount() {
128 | val list1 = listOf(1,2,3,4,5)
129 |
130 | println(" ------ any -------")
131 | // 判断是不是一个集合,若是,则在判断集合是否为空,若为空则返回`false`,反之返回true,若不是集合,则返回`hasNext`
132 | println(list1.any())
133 | // 判断集合中是否有大于10的元素。若存在则返回true,反之返回false
134 | println(list1.any{it > 10})
135 |
136 | println(" ------ all -------")
137 | // 判断集合中是否所有的元素都大于2。若满足条件则返回true,反之返回false
138 | println(list1.all { it > 2 })
139 |
140 | println(" ------ none -------")
141 | // 判断是不是一个集合,若是,则在判断集合是否为空,若为空则返回`false`,反之返回true,若不是集合,则返回`hasNext`
142 | println(list1.none())
143 | // 判断集合中是否所有的元素都大于2。若满足条件则返回true,反之返回false
144 | println(list1.none{ it > 2})
145 |
146 | println(" ------ max -------")
147 | println(list1.max())
148 | println(list1.maxBy { it + 2 })
149 | // println(list1.maxWith(Comparator { num1, num2 -> num1 + num2 }))
150 |
151 | println(" ------ min -------")
152 | println(list1.min()) // 返回集合中最小的元素
153 | println(list1.minBy { it + 2 })
154 | // println(list1.minWith(Comparator { num1, num2 -> num1 + num2 }))
155 |
156 | println(" ------ sum -------")
157 | println(list1.sum())
158 | println(list1.sumBy { it + 2 })
159 | println(list1.sumByDouble { it.toDouble() })
160 |
161 | println(" ------ average -----")
162 | println(list1.average())
163 |
164 | println(" ------ reduce -------")
165 | println(list1.reduce { result, next -> result + next})
166 | println(list1.reduceIndexed { index, result, next ->
167 | index + result + next
168 | })
169 | println(list1.reduceRight { result, next -> result + next })
170 | println(list1.reduceRightIndexed {index, result, next ->
171 | index + result + next
172 | })
173 |
174 | println(" ------ fold -------")
175 | println(list1.fold(3){result, next -> result + next})
176 | println(list1.foldIndexed(3){index,result, next ->
177 | index + result + next
178 | })
179 | println(list1.foldRight(3){result, next -> result + next})
180 | println(list1.foldRightIndexed(3){index,result, next ->
181 | index + result + next
182 | })
183 | }
184 |
185 | /**
186 | * 测试元素操作符
187 | */
188 | private fun optValue() {
189 | val list = listOf("kotlin","Android","Java","PHP","Python","IOS")
190 |
191 | println(" ------ contains -------")
192 | println(list.contains("JS"))
193 |
194 | println(" ------ elementAt -------")
195 |
196 | println(list.elementAt(2))
197 | println(list.elementAtOrElse(10,{it}))
198 | println(list.elementAtOrNull(10))
199 |
200 | println(" ------ get -------")
201 | println(list[2])
202 | println(list.getOrElse(10,{it}))
203 | println(list.getOrNull(10))
204 |
205 | println(" ------ first -------")
206 | println(list.first())
207 | println(list.first{ it == "Android" })
208 | println(list.firstOrNull())
209 | println(list.firstOrNull { it == "Android" })
210 |
211 | println(" ------ last -------")
212 | println(list.last())
213 | println(list.last{ it == "Android" })
214 | println(list.lastOrNull())
215 | println(list.lastOrNull { it == "Android" })
216 |
217 | println(" ------ indexOf -------")
218 | println(list.indexOf("Android"))
219 | println(list.indexOfFirst { it == "Android" })
220 | println(list.indexOfLast { it == "Android" })
221 |
222 | println(" ------ single -------")
223 | val list2 = listOf("list")
224 | println(list2.single()) // 只有当集合只有一个元素时,才去用这个函数,不然都会抛出异常。
225 | println(list2.single { it == "list" }) //当集合中的元素满足条件时,才去用这个函数,不然都会抛出异常。若满足条件返回该元素
226 | println(list2.singleOrNull()) // 只有当集合只有一个元素时,才去用这个函数,不然都会返回null。
227 | println(list2.singleOrNull { it == "list" }) //当集合中的元素满足条件时,才去用这个函数,不然返回null。若满足条件返回该元素
228 |
229 | println(" ------ forEach -------")
230 | list.forEach { println(it) }
231 | list.forEachIndexed { index, it -> println("index : $index \t value = $it") }
232 |
233 | println(" ------ componentX -------")
234 | println(list.component1()) // 等价于`list[0] <=> list.get(0)`
235 | println(list.component2()) // 等价于`list[1] <=> list.get(1)`
236 | println(list.component3()) // 等价于`list[2] <=> list.get(2)`
237 | println(list.component4()) // 等价于`list[3] <=> list.get(3)`
238 | println(list.component5()) // 等价于`list[4] <=> list.get(4)`
239 | }
240 |
241 | /**
242 | * 获取列表或数组元素
243 | */
244 | private fun getElement() {
245 |
246 | val list = listOf("kotlin","Android","Java","PHP","Python","IOS")
247 | /*
248 | 1. 使用get(index)获取
249 | */
250 | val element1 = list[0]
251 |
252 | /*
253 | 2. 使用arr[index]获取
254 | */
255 | val element2 = list[0]
256 |
257 | /*
258 | 3. 使用arr.get
259 | */
260 | val element3 = list.component1()
261 |
262 | println("element1 = $element1 \t element2 = $element2 \t element3 = $element3")
263 |
264 | // val arr = listOf(1,2)
265 | // arr.component4()
266 | }
267 |
268 | /**
269 | * 数组转集合
270 | */
271 | private fun arrayToList() {
272 |
273 | val arr = arrayOf(1,3,5,7,9)
274 | val list = arr.toList()
275 | println("变量arr的类型为:${arr.javaClass}")
276 | println("变量list的类型为:${list.javaClass}")
277 | println(list[1])
278 | }
279 |
280 | /**
281 | * 集合转集合
282 | */
283 | private fun listToList(){
284 | val set = setOf(1)
285 | val list = set.toList()
286 |
287 | println("变量set的类型为:${set.javaClass}")
288 | println("变量list的类型为:${list.javaClass}")
289 | println(list[0])
290 | }
291 |
292 | /**
293 | * 集合转数组
294 | */
295 | private fun listToArray(){
296 | val list = listOf(1,2,3,4,5,6)
297 |
298 | val listArray = list.toIntArray()
299 |
300 | println("变量list的类型为:${list.javaClass}")
301 | println("变量listArray的类型为:${listArray.javaClass}")
302 | println(listArray[1])
303 | }
304 |
305 | fun test(){
306 | listToArray()
307 | arrayToList()
308 | listToList()
309 | getElement()
310 | optValue()
311 | optCount()
312 | optSort()
313 | optMapped()
314 | optFilter()
315 | optProduce()
316 | }
317 |
318 | }
319 |
320 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/ControlStatementDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin语法之控制语句
5 | * author : Jetictors
6 | * time : 2017/9/23 11:35
7 | * version :1.0.1
8 | */
9 | class ControlStatementDemo{
10 |
11 | /**
12 | * 流程控制之if语句
13 | */
14 | private fun ifExample(){
15 |
16 | /* 1. 传统写法 类似Java */
17 | var numA = 2
18 | if (numA == 2){
19 | println("numA == $numA => true")
20 | }else{
21 | println("numA == $numA => false")
22 | }
23 |
24 | /*
25 | 2. Kotlin之中的三元运算符
26 | 在Kotlin中其实是不存在三元运算符( condition ? then : else )这种操作的。
27 | 那是因为if语句的特性(if表达式会返回一个值)故而不需要三元运算符。
28 | */
29 |
30 | // 在Java中可以这么写,但是Kotlin中直接会报错。
31 | // var numB: Int = (numA > 2) ? 3 : 5
32 |
33 | // kotlin中直接用if..else替代。例:
34 | val numB: Int = if ( numA > 2 ) 3 else 5 // 当numA大于2时输出numB的值为5,反之为3
35 | println("numB = > $numB")
36 |
37 | /*
38 | 3. kotlin中if不仅可以作为表达式,也可以作为一个块结构,并且最后一句表达式为块的值
39 | */
40 | val numC: Int = if (numA > 2){
41 | numA++
42 | numA = 10
43 | println("numA > 2 => true")
44 | numA
45 | }else if (numA == 2){
46 | numA++
47 | numA = 20
48 | println("numA == 2 => true")
49 | numA
50 | }else{
51 | numA++
52 | numA = 30
53 | println("numA < 2 => true")
54 | numA
55 | }
56 |
57 | /*
58 | 根据上面的代码可以看出,每一个if分支里面都是一个代码块,并且返回了一个值。根据条件numC的值应该为20
59 | */
60 | println("numC => $numC")
61 |
62 | }
63 |
64 | /**
65 | * 流程控制之for语句
66 | */
67 | private fun forExample(){
68 |
69 | /*
70 | 1. kotlin废除了Java中的for(初始值;条件;增减步长)这个规则。
71 | 但是kotlin中对于for循环语句新增了其他的规则,来满足刚提到的规则。
72 | */
73 |
74 | /*
75 | 递增,并且步长为 1 循环5次
76 | 关键字:until
77 | 范围:until[n,m)
78 | */
79 | for (i in 0 until 5){
80 | print("i => $i \t")
81 | }
82 | println()
83 |
84 | /*
85 | 递减,并且步长为 1 循环5次
86 | 关键字:downTo
87 | 范围:downTo[n,m]
88 | */
89 | for (i in 15 downTo 11){
90 | print("i => $i \t")
91 | }
92 | println()
93 |
94 | /*
95 | for循环默认是递增,下面看另一种方式
96 | 即:for( i in n .. m),范围为[n,m]
97 | */
98 | print("使用 符号`..`的打印结果\n")
99 | for (i in 20 .. 25){
100 | print("i => $i \t")
101 | }
102 |
103 | println()
104 |
105 | print("使用until的打印结果\n")
106 | for (i in 20 until 25){
107 | print("i => $i \t")
108 | }
109 |
110 | println()
111 |
112 | /*
113 | 设置步长
114 | 关键字:step
115 | */
116 | for (i in 10 until 16 step 2){
117 | print("i => $i \t")
118 | }
119 | println()
120 |
121 | /*
122 | 2. 迭代
123 | for循环提供迭代器用来遍历任何东西
124 | for循环数组被编译为一个基于索引的循环,它不会创建一个迭代器对象
125 | */
126 | // 1. 遍历字符串 => 这点在数据类型中的字符串类型中讲过
127 | for (i in "abcdefg"){
128 | print("i => $i \t")
129 | }
130 | println()
131 |
132 |
133 | // 2. 遍历数组 => 这点在数据类型章节中的数组类型中讲过
134 | val arrayListOne = arrayOf(10,20,30,40,50)
135 | for (i in arrayListOne){
136 | print("i => $i \t")
137 | }
138 | println()
139 |
140 | /*
141 | 要遍历具有索引的数组或列表请使用下面两种方式
142 | */
143 | //3.使用数组的indices属性遍历。
144 | val arrayListTwo = arrayOf(1,3,5,7,9)
145 | for (i in arrayListTwo.indices){
146 | println("arrayListTwo[$i] => " + arrayListTwo[i])
147 | }
148 |
149 | // 4. 使用数组的withIndex()方法遍历
150 | for ((index,value) in arrayListTwo.withIndex()){
151 | println("index => $index \t value => $value")
152 | }
153 |
154 | /*
155 | 5. for迭代提供迭代器的任何内容
156 | 即:数组或列表有一个成员或扩展函数iterator()实现了Iterator接口,且该接口提供了next()与hasNext()两个成员或扩展函数
157 | 其一般和while循环一起使用
158 | */
159 | val arrayListThree = arrayOf(2,'a',3,false,9)
160 | val iterator: Iterator = arrayListThree.iterator()
161 |
162 | while (iterator.hasNext()){
163 | println(iterator.next())
164 | }
165 | }
166 |
167 | /**
168 | * 流程控制之when语句
169 | */
170 | private fun whenExample(){
171 | /*
172 | 在Kotlin中已经废除掉了Java中的switch语句。而新增了when(exp){}语句。
173 | when语句不仅可以替代掉switch语句,而且比switch语句更加强大
174 | */
175 |
176 | // 1. when语句实现switch语句功能
177 | when(5){
178 | 1 -> {
179 | println("1")
180 | }
181 | 2 -> println("2")
182 | 3 -> println("3")
183 | 5 -> {
184 | println("5")
185 | }
186 | else -> {
187 | println("0")
188 | }
189 | }
190 |
191 | // 2. 和逗号结合使用,相当于switch语句中的不使用break跳转语句
192 | when(1){
193 | 1 , 2 , 3 -> {
194 | println("1")
195 | }
196 | 5 -> {
197 | println("5")
198 | }
199 | else -> {
200 | println("0")
201 | }
202 | }
203 |
204 | /*
205 | 3. 条件可以使用任意表达式,不仅局限于常量
206 | */
207 | val num:Int = 5
208 | when(num > 5){
209 | true -> {
210 | println("num > 5")
211 | }
212 | false ->{
213 | println("num < 5")
214 | }
215 | else -> {
216 | println("num = 5")
217 | }
218 | }
219 |
220 | /*
221 | 4. 检查值是否存在于集合或数组中.
222 | 使用操作符:
223 | 在(in)
224 | 不在(!in)
225 | 限定:只适用于数值类型
226 | */
227 | val arrayList = arrayOf(1,2,3,4,5)
228 | when(1){
229 | in arrayList.toIntArray() -> {
230 | println("元素`1`存在于 arrayList数组中")
231 | }
232 | in 0 .. 10 -> println("1 属于于 0~10 中")
233 | !in 5 .. 10 -> println("1 不属于 5~10 中")
234 | else -> {
235 | println("都错了 哈哈!")
236 | }
237 | }
238 |
239 | /*
240 | 5. 检查值是否为指定类型的值
241 | 值得注意的是,kotlin智能转换可以访问类型的方法和属性
242 | 使用操作符:
243 | 是(is)
244 | 不是(!is)
245 | */
246 | when("abc"){
247 | is String -> println("abc是一个字符串")
248 | else -> {
249 | println("abc不是一个字符串")
250 | }
251 | }
252 |
253 | var a: Int = 2
254 | when(a){
255 | !is Int -> {
256 | println("$a 不是一个Int类型的值")
257 | }
258 | else -> {
259 | a = a.shl(2)
260 | println("a => $a")
261 | }
262 | }
263 |
264 | /*
265 | 6. 不使用表达式的when语句
266 | 则表示为最简单的布尔表达式
267 | */
268 | val array = arrayOfNulls(3)
269 | when{
270 | true -> {
271 | for (i in array){
272 | print(" $i \t")
273 | }
274 | println()
275 | }
276 | else -> {
277 |
278 | }
279 | }
280 |
281 | }
282 |
283 | /**
284 | * 流程控制之while语句
285 | */
286 | private fun whileExample(){
287 | /*
288 | Kotlin中的while循环同Java中的一样,其定义格式为:
289 | while(exp){ 其中exp为表达式
290 | ...
291 | }
292 | */
293 |
294 | var num = 5
295 | var count = 1
296 | while (num < 10){
297 | println("num => $num")
298 | println("循环了$count 次")
299 | count++
300 | num++
301 | }
302 |
303 | }
304 |
305 | /**
306 | * 流程控制之do..while语句
307 | */
308 | private fun doWhileExample(){
309 |
310 | /*
311 | Kotlin中的while循环同Java中的一样,其定义格式为:
312 | do{...}while(exp)
313 | */
314 | var num = 5
315 | var count = 1
316 | do {
317 | println("num => $num")
318 | println("循环了$count 次")
319 | count++
320 | num++
321 | }while (num < 10)
322 |
323 | // do{...}while(exp)与while(exp){...}最大的区别是do{...}while(exp)最少执行一次
324 |
325 | num = 5
326 | count = 1
327 | do {
328 | println("num => $num")
329 | println("循环了$count 次")
330 | count++
331 | num++
332 | }while (num < 5)
333 | }
334 |
335 | /**
336 | * 流程控制之控制语句
337 | * 1. return
338 | * 2. break
339 | * 3. continue
340 | */
341 | private fun controlExample(){
342 | /*
343 | 1. return语句,同Java中的return语句一样
344 | 默认情况下,从最近的封闭函数或匿名函数返回。
345 | */
346 | returnExample()
347 |
348 | /*
349 | 2. break语句,同Java中的break语句一样
350 | 终止最近的闭合循环。
351 | */
352 | breakExample()
353 |
354 | /*
355 | 3. continue语句,同Java中的continue语句一样
356 | 前进到最近的封闭循环的下一个步骤(迭代)。
357 | */
358 | continueExample()
359 | }
360 |
361 | private fun continueExample() {
362 | for (i in 1 until 10){
363 | if (i == 5){
364 | println("我跳过了第$i 次循环")
365 | continue
366 | }
367 | println("i => $i")
368 | }
369 | }
370 |
371 | private fun breakExample() {
372 | var count: Int = 1
373 | for (i in 1 until 10){
374 | if (i == 5){
375 | println("我在第$i 次退出了循环")
376 | break
377 | }
378 | count++
379 | }
380 | println("我循环了多少次:count => $count")
381 | }
382 |
383 | private fun returnExample(){
384 | val str: String = ""
385 | if (str.isBlank()){
386 | println("我退出了该方法")
387 | return
388 | }
389 | }
390 |
391 | fun test() {
392 | ifExample()
393 | forExample()
394 | whileExample()
395 | doWhileExample()
396 | whenExample()
397 | controlExample()
398 | }
399 |
400 | }
401 |
--------------------------------------------------------------------------------
/src/main/java/com/kotlin/leran/basis/DataTypeDemo.kt:
--------------------------------------------------------------------------------
1 | package com.kotlin.leran.basis
2 |
3 | /**
4 | * 描述 : Kotlin语法之数据类型详解
5 | * author : Jetictors
6 | * time : 2017/9/2 22:01
7 | * version : 1.0.1
8 | */
9 |
10 | class DataTypeDemo{
11 |
12 | /**
13 | * 数字类型
14 | * 1. Byte : 8位
15 | * 2. Short : 16位
16 | * 3. Int : 32位
17 | * 4. Long : 64位
18 | * 5. Float : 32位
19 | * 6. Double : 64位
20 | */
21 | private fun numberType(){
22 | val a: Byte = 2
23 | val b: Short = 2
24 | val c: Int = 2
25 | val d: Long = 2L //长整型由大写字母L标记
26 | val e: Float = 2.0f //单精度浮点型由小写字母f或大写字符F标记
27 | val f: Double = 2.0
28 | val g = 0x0F //十六进制数
29 | val h = 0b00001011 //二进制数
30 | val k = 123 //十进制数
31 | //ps: kotlin是不支持八进制数的
32 |
33 | println(" a => $a \n b => $b \n c => $c \n d => $d \n e => $e \n f => $f \n g => $g \n h => $h \n k => $k" +
34 | " \n 切记:kotlin是不支持八进制数")
35 |
36 | /*
37 | 数字类型字面常量的下划线
38 | 作用:分割数字进行分组
39 | */
40 | val oneMillion = 1_000_000
41 | val creditCardNumber = 1234_5678_9012_3456L
42 | val socialSecurityNumber = 999_99_9999L
43 | val hexBytes = 0xFF_EC_DE_5E
44 | val bytes = 0b11010010_01101001_10010100_10010010
45 |
46 | println("oneMillion => $oneMillion")
47 | println("creditCardNumber => $creditCardNumber")
48 | println("socialSecurityNumber => $socialSecurityNumber")
49 | println("hexBytes => $hexBytes")
50 | println("bytes => $bytes")
51 |
52 | /*
53 | 装箱
54 | */
55 | val numValue: Int = 127
56 | //装箱的过程
57 | val numValueBox : Int? = numValue
58 | println("装箱后: numValueBox => $numValueBox")
59 |
60 | /*
61 | 比较两个数字
62 | */
63 | var result: Boolean
64 | result = numValue == numValueBox
65 | println("numValue == numValueBox => $result") // => true,其值是相等的
66 |
67 |
68 | result = numValue === numValueBox
69 | println("numValue === numValueBox => $result") // => false,其地址是不一样的
70 |
71 |
72 | /*
73 | 显示转换
74 | 较小的类型不会被隐式转换为更大的类型,故而系统提供了显示转换
75 | */
76 | val numA: Int = 97
77 | println(numA.toByte())
78 | println(numA.toShort())
79 | println(numA.toInt())
80 | println(numA.toFloat())
81 | println(numA.toDouble())
82 | println(numA.toLong())
83 | println(numA.toChar())
84 | println(numA.toString())
85 |
86 | /*
87 | 隐式转换
88 | 类型是从上下文推断出来的
89 | 而算术运算则被重载为适当的转换
90 | */
91 | // 30L + 12 -> Long + Int => Long
92 | val num = 30L + 12
93 | print(num)
94 |
95 | /*
96 | 位运算符
97 | 支持序列如下:shl、shr、ushr、and、or、xor
98 | */
99 | val operaNum: Int = 4
100 |
101 | val shlOperaNum = operaNum shl(2)
102 | val shrOperaNum = operaNum shr(2)
103 | val ushrOperaNum = operaNum ushr(2)
104 | val andOperaNum = operaNum and(2)
105 | val orOperaNum = operaNum or(2)
106 | val xorOperaNum = operaNum xor(2)
107 | val invOperaNum = operaNum.inv()
108 |
109 | println("shlOperaNum => $shlOperaNum \n " +
110 | "shrOperaNum => $shrOperaNum \n " +
111 | "ushrOperaNum => $ushrOperaNum \n " +
112 | "andOperaNum => $andOperaNum \n " +
113 | "orOperaNum => $orOperaNum \n " +
114 | "xorOperaNum => $xorOperaNum \n " +
115 | "invOperaNum => $invOperaNum")
116 |
117 | }
118 |
119 | /**
120 | * 字符型
121 | */
122 | private fun charType(){
123 | //字符由Char类型表示,它不能直接同视为数字,不过可以显示转换
124 | val char1: Char = 'a'
125 | //char1 = 1 //=> 这句代码会直接出错
126 | println("char1 => $char1")
127 |
128 | /*
129 | 字符显示转换
130 | */
131 | val val1 = char1.toByte()
132 | val val2 = char1.toInt()
133 | val val3 = char1.toString()
134 | val val4 = char1.toFloat()
135 | val val5 = char1.toShort()
136 | println("val1 => $val1 \n val2 => $val2 \n val3 => $val3 \n val4 => $val4 \n val5 => $val5")
137 |
138 | /*
139 | 当字符变量为英文字母时,大小写的转换
140 | */
141 | val charA: Char = 'a'
142 | val charB: Char = 'B'
143 | val charNum: Char = '1'
144 | var result: Char
145 |
146 | // 转换为大写
147 | result = charA.toUpperCase()
148 | println("result => $result")
149 |
150 | // 转换为小写
151 | result = charB.toLowerCase()
152 | println("result => $result")
153 |
154 | //当字符变量不为英文字母时,转换无效
155 | result = charNum.toLowerCase()
156 | println("result => $result")
157 |
158 | /*
159 | 转义字符
160 | 同Java一样,使用某些特殊的字符时,要使用转义。
161 | 需转义的字符如下:
162 | \t => 表示制表符
163 | \n => 表示换行符
164 | \b => 表示退格键(键盘上的Back建)
165 | \r => 表示键盘上的`Enter`键
166 | \\ => 表示反斜杠
167 | \' => 表示单引号
168 | \" => 表示双引号
169 | \$ => 表示美元符号,如果不转义在kotlin中就表示变量的引用了
170 | 其他的任何字符请使用Unicode转义序列语法。例:'\uFF00'
171 | */
172 | println("\n 换行符")
173 | println("\t 制表符")
174 | println(" \b 退格键")
175 | println("\r Enter键同样换行")
176 | println('\\')
177 | println('\'')
178 | println('\"')
179 | println('\$')
180 | println('\uFF01')
181 |
182 | }
183 |
184 | /**
185 | * Boolean型
186 | */
187 | private fun booleanType(){
188 | /*
189 | 定义:
190 | */
191 | val isNum: Boolean = false
192 | println("isNum => $isNum")
193 |
194 | /*
195 | 操作运算符
196 | ' || ' => 逻辑或(或者)
197 | ' && ' => 逻辑与(并且)
198 | ' ! ' => 逻辑非(取反)
199 | */
200 | val a: Boolean = false
201 | val b: Boolean = true
202 | var result: Boolean
203 |
204 | /* 逻辑或操作 */
205 | if (a || b){
206 | result = a || b
207 | println("a || b => $result")
208 | }
209 |
210 | /* 逻辑与操作 */
211 | if (a && b){
212 | result = a && b
213 | println("a && b => $result")
214 | }
215 |
216 | /* 逻辑非操作 */
217 | result = !a
218 | println("!a => $result")
219 |
220 | result = !b
221 | println("!b => $result")
222 |
223 | }
224 |
225 | /**
226 | * 数组类型
227 | */
228 | private fun arrayType(){
229 | /*
230 | kotlin中数组由Array表示,可以去看看源码实现,里面就几个方法
231 | 创建数组的3个函数
232 | */
233 |
234 | // 1. arrayOf() => 参数是一个可变参数的泛型对象
235 | val arr1 = arrayOf(1,2,3,4,5) //等价于[1,2,3,4,5]
236 | for (v in arr1){
237 | print(v)
238 | print("\t")
239 | }
240 |
241 | println()
242 |
243 | val arr2 = arrayOf("0","2","3",'a',32.3f)
244 | for (v in arr2){
245 | print(v)
246 | print("\t")
247 | }
248 |
249 | println()
250 |
251 | // 2. arrayOfNulls() =>用于创建一个指定数据类型且可以为空元素的给定元素个数的数组
252 | val arr3 = arrayOfNulls(3)
253 |
254 | //如若不予数组赋值则arr3[0]、arr3[1]、arr3[2]皆为null
255 | for(v in arr3){
256 | print(v)
257 | print("\t")
258 | }
259 |
260 | println()
261 |
262 | //为数组arr3赋值
263 | arr3[0] = 10
264 | arr3[1] = 20
265 | arr3[2] = 30
266 |
267 | for(v in arr3){
268 | print(v)
269 | print("\t")
270 | }
271 |
272 | println()
273 |
274 | /*
275 | 3. 使用一个工厂函数,它使用数组大小和返回给定其索引的每个数组元素的初始值的函数
276 | Array() => 第一个参数表示数组元素的个数,第二个参数则为使用其元素下标组成的表达式
277 | */
278 | val arr4 = Array(5) { index -> (index * 2).toString() }
279 | for (v in arr4){
280 | print(v)
281 | print("\t")
282 | }
283 |
284 | println()
285 |
286 | /*
287 | 在kotlin中数组类型与Java不同的是,kotlin中的数组是不变的,这样可以防止可能的运行时故障
288 | 类型投影:这一点在泛型章节中会详细的介绍。这里不多做累述
289 | */
290 |
291 | /*
292 | Kotlin还有专门的类来表示原始类型的数组,没有装箱开销.
293 | ByteArray
294 | ShortArray
295 | IntArray
296 | LongArray
297 | BooleanArray
298 | CharArray
299 | FloatArray
300 | DoubleArray
301 | */
302 | val intArr: IntArray = intArrayOf(1,2,3,4,5)
303 | for (number in intArr){
304 | print(number)
305 | print("\t")
306 | }
307 |
308 | println()
309 |
310 | val charArr: CharArray = charArrayOf('a','1','b','c','3','d')
311 | for (char in charArr){
312 | print(char)
313 | print("\t")
314 | }
315 |
316 | println()
317 |
318 | val longArr: LongArray = longArrayOf(12L,1254L,123L,111L)
319 | for (long in longArr){
320 | print(long)
321 | print("\t")
322 | }
323 | }
324 |
325 | /**
326 | * 字符串类型
327 | */
328 | private fun stringType(){
329 | // 1. 字符串由String类型表示。并且其是不可变的。字符串的元素可以通过索引操作的字符:s[i]来访问。可以使用for循环迭代字符串:
330 | val str: String = "kotlin"
331 | println("str => $str")
332 |
333 | //迭代
334 | for (s in str){
335 | print(s)
336 | print("\t")
337 | }
338 | print("\n")
339 |
340 | /*
341 | 2. 字符串字面量,在kotlin中有两种类型:
342 | - 包含转义字符的字符串 转义包括('\t','\n'等)
343 | - 包含任意字符的字符串 由三重引号包括(""" .... """)
344 | */
345 | var str1: String = "hello\t\tkotlin"
346 | println(str1)
347 | str1 = "hello kotlin"
348 | println(str1)
349 |
350 | val str2 = """ fun main(args: Array){
351 | println("我是三重引号引用的字符串,我可以包含任意字符")
352 | } """
353 | println(str2)
354 |
355 | //可以使用trimMargin()函数删除前导空格 默认使用符号('|')作边距前缀,当然也可以使用其他字符。例:('>','<'等)
356 | val str3: String = """
357 | > I`m like Kotlin .
358 | > I`m like Java .
359 | > I`m like Android .
360 | > I`m like React-Native.
361 | """.trimMargin(">")
362 | println(str3)
363 |
364 |
365 | /*
366 | 字符串模板
367 | 使用字符串模板的符号为('$').
368 | 在$符号后面加上变量名或大括号中的表达式
369 | */
370 | val text1: String = "我来了!"
371 | val text2: String = "$text1 kotlin"
372 | val text3: String = "$text2 ${text1.length} 哈哈!!!!"
373 | println(text1)
374 | println(text2)
375 | println(text3)
376 | }
377 |
378 | fun test(){
379 | numberType()
380 | booleanType()
381 | charType()
382 | arrayType()
383 | stringType()
384 | }
385 |
386 | }
--------------------------------------------------------------------------------