Skip to content

Commit

Permalink
Update 1.Kotlin_简介&变量&类&接口.md
Browse files Browse the repository at this point in the history
  • Loading branch information
CharonChui authored Sep 6, 2023
1 parent e6e90f0 commit 020e8a5
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion KotlinCourse/1.Kotlin_简介&变量&类&接口.md
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ class Test{
那lateinit有什么用呢? 每次使用还要判断isInitialized。
The primary use-case for lateinit is when you can't initialize a property in the constructor but can guarantee that it's initialized "early enough" in some sense that most uses won't need an isInitialized check. E.g. because some framework calls a method initializing it immediately after construction.
Lateinit Initialization is used when you want to initialize a variable at a later stage, especially when it's non-null and must be initialized before use.
It's commonly used in dependency injection and testing.
除了使用`lateinit`外还可以使用`by lazy {}`效果是一样的:
```kotlin
Expand All @@ -417,7 +421,8 @@ test is not null haha
- `by lazy{}`只能用在`val`类型而`lateinit`只能用在`var`类型
- `lateinit`不能用在可空的属性上和`java`的基本类型上,否则会报`lateinit`错误
- lateinit在分配之前不会初始化变量,而by lazy在第一次访问时初始化它。
- 如果在初始化之前访问,lateinit会抛出异常,而lazy则可以确保已初始化。
lazy的背后是接收一个lambda并返回一个Lazy<T>实例的函数,第一次访问该属性时,会执行lazy对应的Lambda表达式并记录结果,后续访问该属性时只是返回记录的结果。
另外系统会给lazy属性默认加上同步锁,也就是LazyThreadSafetyMode.SYNCHRONIZED,它在同一时刻只允许一个线程对lazy属性进行初始化,所以它是线程安全的。
Expand Down

0 comments on commit 020e8a5

Please sign in to comment.