Kotlin?- lateinit vs lazy

(翻譯)

學習Kotlin——lateinit vs lazy

lateinit vs lazy

在Kotlin中有許多優(yōu)秀的特性迄埃,我們可以利用所有這些特性在Kotlin中編寫更好的應用程序棉姐。在所有這些特性中妄均,lateinit和lazy是重要的屬性初始化特性荐类。我們必須知道何時使用哪個屬性初始化境肾。

Kotlin 屬性初始化

如果您不想在構造函數(shù)中初始化屬性蚂夕,那么這是Kotlin中屬性初始化的兩種重要方法。

  • lateinit
  • lazy

lateinit

lateinit是后期初始化佩谷。

通常旁壮,聲明為非空類型的屬性必須在構造函數(shù)中初始化。然而谐檀,這通常是不方便的寡具。例如,可以通過依賴項注入或在單元測試的設置方法中初始化屬性稚补。在這種情況下,您不能在構造函數(shù)中提供非空初始化器框喳,但在引用類體內(nèi)的屬性時课幕,仍然希望避免空檢查。

要處理這種情況五垮,可以使用lateinit修飾符標記屬性乍惊。

例子

public class Test {

  lateinit var mock: Mock

  @SetUp fun setup() {
     mock = Mock()
  }

  @Test fun test() {
     mock.do()
  }
}

修飾符只能用于類主體中聲明的var屬性(不在主構造函數(shù)中),并且只有在屬性沒有自定義的getter或setter時才可以使用放仗。屬性的類型必須是非空的润绎,并且不能是原始類型。

lazy

lazy 就是延遲初始化。

lazy()是一個接受lambda并返回一個lazy實例的函數(shù)莉撇,該實例可以作為實現(xiàn)lazy屬性的委托:對get()的第一個調(diào)用執(zhí)行傳遞給lazy()的lambda并記住結果呢蛤,對get()的后續(xù)調(diào)用只返回記住的結果。

例子

public class Example{
  val name: String by lazy { “Amit Shekhar” }
}

所以第一次調(diào)用和隨后的調(diào)用棍郎,名字會返回" Amit Shekhar "

現(xiàn)在其障,如何選擇何時使用哪一個?

  • lazy只能用于val屬性,而lateinit只能應用于vars涂佃,因為它不能編譯成final字段励翼,因此不能保證不變性。
  • lateinit變量可以在任何對象被看到的地方初始化辜荠。如果您希望以一種可能事先未知的方式從外部初始化您的屬性汽抚,請使用lateinit。

(原文)

Learn Kotlin?—? lateinit vs lazy

lateinit vs lazy

There are many great features available in Kotlin, we can take advantage of all these features to write the better application in Kotlin. Among all those features, lateinit and lazy are important property initialization feature. We must know when to use which property initialization.

Kotlin Property Initialization

If you do not want to initialize a property in the constructor, then these are two important ways of property initialisation in Kotlin.

  • lateinit
  • lazy

lateinit

lateinit is late initialization.

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

To handle this case, you can mark the property with the lateinit modifier.

Example

public class Test {

  lateinit var mock: Mock

  @SetUp fun setup() {
     mock = Mock()
  }

  @Test fun test() {
     mock.do()
  }
}

The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.

lazy

lazy is lazy initialization.

lazy() is a function that takes a lambda and returns an instance of lazy which can serve as a delegate for implementing a lazy property: the first call to get() executes the lambda passed to lazy() and remembers the result, subsequent calls to get() simply return the remembered result.

Example

public class Example{
  val name: String by lazy { “Amit Shekhar” }
}

So the first call and the subsequent calls, name will return “Amit Shekhar”

Now, How to choose when to use which one?

  • lazy can only be used for val properties, whereas lateinit can only be applied to vars because it can’t be compiled to a final field, thus no immutability can be guaranteed.
  • lateinit var can be initialized from anywhere the object is seen from. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

原文鏈接 https://blog.mindorks.com/learn-kotlin-lateinit-vs-lazy

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末伯病,一起剝皮案震驚了整個濱河市造烁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌狱从,老刑警劉巖膨蛮,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異季研,居然都是意外死亡敞葛,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進店門与涡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來惹谐,“玉大人,你說我怎么就攤上這事驼卖“奔。” “怎么了?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵酌畜,是天一觀的道長怎囚。 經(jīng)常有香客問我,道長桥胞,這世上最難降的妖魔是什么恳守? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮贩虾,結果婚禮上催烘,老公的妹妹穿的比我還像新娘。我一直安慰自己缎罢,他們只是感情好伊群,可當我...
    茶點故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布考杉。 她就那樣靜靜地躺著,像睡著了一般舰始。 火紅的嫁衣襯著肌膚如雪崇棠。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天蔽午,我揣著相機與錄音易茬,去河邊找鬼。 笑死及老,一個胖子當著我的面吹牛抽莱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播骄恶,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼食铐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了僧鲁?” 一聲冷哼從身側響起虐呻,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎寞秃,沒想到半個月后斟叼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡春寿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年朗涩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绑改。...
    茶點故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡谢床,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出厘线,到底是詐尸還是另有隱情识腿,我是刑警寧澤,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布造壮,位于F島的核電站渡讼,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏耳璧。R本人自食惡果不足惜硝全,卻給世界環(huán)境...
    茶點故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望楞抡。 院中可真熱鬧,春花似錦析藕、人聲如沸召廷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽竞慢。三九已至先紫,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間筹煮,已是汗流浹背遮精。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留败潦,地道東北人本冲。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像劫扒,于是被迫代替她去往敵國和親檬洞。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,614評論 2 353