我是 Kotlin 的新手并正在學習它。我想出了一些高級語法。
abstract class BaseVMActivity(VM:ViewModel,B:ViewBinding) => This is I know as constructor.
但
abstract class BaseVMActivity<VM : ViewModel , B : ViewBinding> => This syntax I didn't understand.
它與建構式有何不同?
uj5u.com熱心網友回復:
with 的語法<>用于泛型型別引數,它獨立于建構式。從技術上講,您可以同時擁有兩者:
class BaseVMActivity<VM : ViewModel , B : ViewBinding>(vm: VM, b: B)
您可以在檔案中閱讀一些關于泛型的內容,但該檔案更側重于與 Java 的差異(例如關于泛型差異),而不是解釋泛型的基礎知識。@Tenfour04 提到的Java 檔案更具指導意義。
基本上,當類的代碼除了類的某些輸入/輸出值的型別(建構式/方法引數和回傳型別)之外應該相同時,泛型類很有用。它允許擁有更多的型別安全性,而不僅僅是Any在任何地方使用或其他父型別。
例如,此類Box可以包含任何型別的值:
class Box(var value: Any)
但是當你得到一個實體時,Box你無法在編譯時知道它包含什么:訪問box.value會給你一個 type 的值Any,你需要轉換它(在運行時冒著失敗的風險)以獲得一個可用的值:
val box: Box = Box("some string")
val value1: String = box.value // not allowed
val value2: String = box.value as String // risky if box is declared somewhere else
val value3: Int = box.value as Int // compiles fine, fails at runtime
泛型是添加編譯時安全性的好方法。這是宣告泛型Box<T>類的方法,在T實體化類時決定的型別在哪里。T被說成是一個型別引數的的Box類。的不同實體Box可以使用不同的型別T(它們可以具有不同型別的值):
class Box<T>(var value: T)
val box: Box<String> = Box("some string")
// this compiles and is safe, because it's a Box<String>, not any box
val value: String = box.value
val value: Int = box.value // doesn't compile
val value: Int = box.value as Int // doesn't compile, because String can't be cast to Int
現在這Box<T>可以用于任何型別T,但有時您想限制該型別僅接受某些型別。這是語法的:來源:
abstract class Animal
class Dog : Animal()
class Cat : Animal()
class Box<T : Animal>(val animal: T)
如果我這樣宣告Box,則只Animal允許子型別:
val catBox: Box<Cat> = Box(Cat())
val dogBox: Box<Dog> = Box(Dog())
val stringBox: Box<String> = Box("some string") // doesn't compile
您還可以通過用逗號分隔來在泛型類中宣告多個型別引數:
interface Map<K, V>
每個型別引數也可以有自己的邊界,這就是您所看到的語法的原因:
abstract class BaseVMActivity<VM : ViewModel , B : ViewBinding>
在這種情況下,有 2 個型別引數VMand B,它們必須分別是ViewModeland 的子型別ViewBinding。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/382580.html
標籤:安卓 安卓工作室 科特林 捆绑 android-viewmodel
