Kotlin: @JvmStatic and Kotlin Data Types
這幾天面試真的都是被打臉,
------
上面這個 @JvmStatic 是啥意思呢?
有面試官問我Kotlin的變數基本型態有那些,當下我答得不好.
像這種基本型態的問題....
都需要隨時複習一次.
Kotlin has the following basic data types:
1. Numbers – Byte, Short, Int, Long, Float, Double
2. Boolean – True, false
3. Characters: Char
4. Arrays //val numbers = IntArray(5)
5. Strings
Type | Size | Range |
---|---|---|
Byte | 8 bits | -128 to 127 |
Short | 16 bits | -32,768 to 32,767 |
Int | 32 bits | -2,147,483,648 to 2,147,483,647 |
Long | 64 bits | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Every number type has the following conversion functions:
- toByte(): Byte
- toShort(): Short
- toInt(): Int
- toLong(): Long
- toFloat(): Float
- toDouble(): Double
- toChar(): Char
fun main() { val x:Long = 23_334 val y:Int = x.toInt() println(x) println(y) }
基本上面試官問這種問題,實在不恰當,這種東西是屬於 reference 性質,
就算背的苦瓜爛熟,又有何用?
----
char:
fun main() { for (c in 'a'..'k') print("$c ") println() for (c in 'k' downTo 'a') print("$c ") }
.
------
@JvmStatic
fun calcute_total_elec_fee(
f_use_watt: Float,
f_use_hour: Float,
f_elec_every_unit_fee: Float,
i_month_using_days: Int
): Double {
....
}
上面這個 @JvmStatic 是啥意思呢?
將命名對像或 companion object中定義的函數註解為 @JvmStatic
使用此註解後,編譯器將在對象的封閉類中生成靜態方法或靜態屬性.
且注意 @JvmStatic 只能在object類或companion object中使用.
而@JvmField沒有這些限制
Companion:
Kotlin中我們可以藉助object實現靜態的形式,比如下面的代碼
class C {
companion object {
@JvmStatic
fun foo() {}
fun bar() {}
}
}
----
@JvmField
-消除了variable的getter與setter方法
-把variable屬性用public 暴露出來
example:
class Developer (@JvmField val name: String, val ide: String)
so:
Developer developer = new Developer("Andy", "Android Studio");
System.out.println(developer.getIde());// not using JvmField
System.out.println(developer.name);// using JvmField
使用@JvmField,我們在Java中調用的時候,可以直接使用屬性名,而不是對應的getter方法。
留言
張貼留言