Kotlin Collection
Collection
Time: 2022-1-31
首先得知道Collection是kotlin-stdlib里面的东西。
TypeKotlin的集合框架有如下的类型
List
List is an ordered collection with access to elements by indices – integer numbers that reflect their position. Elements can occur more than once in a list. An example of a list is a telephone number: it’s a group of digits, their order is important, and they can repeat.
List是一个有序的几口,通过一个下标来索引与那苏,(一个integer来反映元素的位置)
元素在List内可以重复出现
简单的例子如电话号码,他是数字的一个List,可以重复。
Set
Set is a collection of unique elemen ...
Kotlin协程
关于本篇文章是记录的在协程源码分析的内容合集
Suspend function 1 ——Source
Time :2022-1-14——利用Kotlin ByteCode插件对挂起函数进行分析。(这个插件不是很好用。)
Time:2022-1-24——使用Jadx对编译后打包的jar包进行分析
概述
挂起函数初探
挂起函数是什么?
挂起函数能干什么?
那些是挂起函数?
挂起函数怎么实现的?
挂起函数是什么挂起函数本质还是函数,只不过这个函数在经过Kotlin编译器以后会进行一些特殊的处理。以达到用同步的代码写出异步的操作逻辑。
挂起函数能干什么就简单而言,挂起函数具有以下两种功能。
——挂起,恢复。
由于这两种功能使得挂起函数具备了——使用同步的写法,达到了异步的逻辑。
哪些是挂起函数我觉得标题改为 怎么定义,使用挂起函数。会更加贴合实际。hh
关于什么是挂起函数很简单。
这是挂起函数的定义,和普通函数的定义其实是一致的。
123suspend fun suspendFunc1(){}
除此之外还有一种奇怪的定义方式。(其实也不是很奇怪啦,上面是挂起函数的‘常 ...
Kotlin委托
委托Kotlin对于委托是开箱支持的,委托是一种消除样板代码的方式
The Delegation pattern has proven to be a good alternative to implementation inheritance, and Kotlin supports it natively requiring zero boilerplate code.
接口委托一个类可以实现一个接口,然后把这个接口的公开方法委托给另外一个类。
words is cheap ,give me the code
12345678910111213141516171819interface Base { fun print()}class BaseDelegate: Base { override fun print() { println("我是Base的Delegate我现在非常的后悔,为啥我要给BaseImp背锅") }}class BaseImp(delegate ...
Kotlin契约
ContractContract的中文叫做协议,协约,合同。
这个合同呢是和编译器签订的。
kotlin的编译器比较聪明但是不是太聪明。
所以有的时候会犯傻hh。
引入Contract比如这同样。
ensureNotNullAndEmpty已经确定了str不为空,也不为””
但是使用的时候编译器还是认为这个东西可能是空的。
如果这个时候我们想告诉编译器这个东西不是空的,那该怎么弄。
这就得使用contract了
很简单就修改一下代码
123456789@OptIn(ExperimentalContracts::class)fun String?.ensureNotNullAndEmpty(): Boolean { contract { returns(true) implies (this@ensureNotNullAndEmpty != null) } return this != null && !isEmpty()}
这样就不报错了
Contract使用Contract内部的内容比较少
...
Hilt学习笔记
Hilt
Hilt 是 一个依赖注入框架,对此Google并没有强迫我们去使用依赖注入。主要是因为我们需要依赖注入,而且对于大型项目更是如此。
假想你有一个项目,里面用了很多的官方框架,第三方框架,对于一些其中的工具的实例你肯定不能在使用的时候直接new。
主要有两个原因
1.资源浪费
如果是通用的‘工具’通常情况下是会将其声明为Application作用域下的单例,因为每new一个会消耗大量的资源,比如Retrofit和Gson等。
2.耦合性
如果我们在使用的时候自己配置或者new一个工具,当项目的依赖库发生变动的时候,haha,只能一个一个自己去改,小项目倒也没啥,如果是大项目,开篇一搜索就是1w+的引用就问你怕不怕。
另外
依赖注入不是Hilt的特殊功能,依赖注入是一种实现依赖关系解耦合的方法。
说到这里了那就讲讲什么是依赖注入
依赖注入即dependency injection,只要变量是由外部初始化的都叫依赖注入
实现依赖注入有三种
构造函数注入:依赖关系是通过 class 构造器提供的。
像这样
12345fun main() { DI01(&qu ...