Šioje pamokoje sužinosite apie kintamuosius, kaip juos sukurti ir pagrindinius duomenų tipus, kuriuos „Kotlin“ palaiko kuriant kintamuosius.
Kaip žinote, kintamasis yra vieta atmintyje (saugojimo sritis), kurioje laikomi duomenys.
Norint nurodyti saugyklos plotą, kiekvienam kintamajam turėtų būti suteiktas unikalus pavadinimas (identifikatorius). Sužinokite daugiau apie tai, kaip pavadinti kintamąjį „Kotlin“?
Kaip deklaruoti kintamąjį Kotlin?
Norint deklaruoti kintamąjį Kotlin, naudojamas arba, var
arba val
raktinis žodis. Štai pavyzdys:
var language = "prancūzų" val score = 95
Var ir val naudojimo skirtumai aptariami vėliau straipsnyje. Kol kas sutelkime dėmesį į kintamųjų deklaravimą.
Čia kalba yra tipo kintamasis String
, ir score
yra tipo kintamasis Int
. Jums nereikia nurodyti kintamųjų tipo; Kotlinas tai netiesiogiai daro už jus. Kompiliatorius tai žino pagal inicializatoriaus išraišką („prancūzų“ yra a String
, o 95 yra sveiko skaičiaus reikšmė aukščiau pateiktoje programoje). Programavime tai vadinama tipo išvada.
Tačiau, jei norite, galite aiškiai nurodyti tipą:
var kalba: stygos = „prancūzų“ val rezultatas: vidurkis = 95
Aukščiau pateiktuose pavyzdžiuose deklaruodami kintamąjį inicijavome. Tačiau tai nėra būtina. Galite deklaruoti kintamąjį ir nurodyti jo tipą viename sakinyje, o vėliau - inicializuoti kintamąjį kitame sakinyje vėliau.
var language: String // kintamasis tipo deklaravimas String… language = "prancūzų" // kintamojo inicijavimas
Čia yra keletas pavyzdžių, dėl kurių atsiranda klaida.
var kalba // Klaidos kalba = "prancūzų"
Čia kalbos kintamojo tipas nėra aiškiai nurodytas, o kintamasis nėra inicijuojamas deklaruojant.
var language: String language = 14 // Klaida
Čia mes bandome priskirti 14 (sveiko skaičiaus reikšmę) skirtingo tipo kintamajam ( String
).
Skirtumas tarp var ir val
- val (Nekintama nuoroda) - kintamojo, deklaruoto naudojant
val
raktinį žodį, negalima pakeisti priskyrus vertę. Tai panašu į galutinį „Java“ kintamąjį. - var (kintama nuoroda) - kintamąjį, deklaruotą naudojant
var
raktinį žodį, vėliau programoje galima pakeisti. Tai atitinka įprastą „Java“ kintamąjį.
Štai keli pavyzdžiai:
var language = "prancūzų" language = "vokiečių"
Čia language
kintamasis priskiriamas vokiečių k. Kadangi kintamasis deklaruojamas naudojant var
, šis kodas veikia puikiai.
val kalba = "prancūzų" kalba = "vokiečių" // klaida
German
Ankstesniame pavyzdyje negalite priskirti kalbos kintamojo, nes kintamasis deklaruojamas naudojant val
.
Dabar jūs žinote, kokie yra „Kotlin“ kintamieji, laikas išmokti skirtingų „Kotlin“ kintamųjų reikšmių.
„Kotlin“ pagrindiniai tipai
„Kotlin“ yra statiškai įvesta kalba, tokia kaip „Java“. Tai yra, kad kintamojo tipas yra žinomas kompiliavimo metu. Pavyzdžiui,
val kalba: Int val ženklai = 12.3
Čia kompiliatorius žino, kad kalba yra tipo Int
, o žymės yra tipo Double
prieš kompiliavimo laiką.
„Kotlin“ įmontuotus tipus galima suskirstyti į:
- Skaičiai
- Personažai
- Booleanai
- Masyvai
Skaičiaus tipas
Skaičiai Kotlin yra panašūs į „Java“. Yra 6 įmontuoti tipai, žymintys skaičius.
- Baitas
- Trumpas
- Vid
- Ilgas
- Plūdė
- Dvigubai
1. Baitas
Byte
Duomenų tipas gali turėti reikšmes nuo -128 iki 127 (8 bitų pasirašė dvi įgula sveikasis skaičius).- It is used instead of
Int
or other integer data types to save memory if it's certain that the value of a variable will be within (-128, 127) - Example:
fun main(args : Array) ( val range: Byte = 112 println("$range") // The code below gives error. Why? // val range1: Byte = 200 )
When you run the program, the output will be:
112
2. Short
- The
Short
data type can have values from -32768 to 32767 (16-bit signed two's complement integer). - It is used instead of other integer data types to save memory if it's certain that the value of the variable will be within (-32768, 32767).
- Example:
fun main(args : Array) ( val temperature: Short = -11245 println("$temperature") )
When you run the program, the output will be:
-11245
3. Int
- The
Int
data type can have values from-231
to231-1
(32-bit signed two's complement integer). - Example:
fun main(args : Array) ( val score: Int = 100000 println("$score") )
When you run the program, the output will be:
100000
If you assign an integer between -231
to 231-1
to a variable without explicitly specifying its type, the variable will be of Int
type. For example,
fun main(args : Array) ( // score is of type Int val score = 10 println("$score") )
If you are using IntelliJ IDEA, you can place cursor inside the variable and press Ctrl + Shift + P
to see its type.
4. Long
- The
Long
data type can have values from-263
to263-1
(64-bit signed two's complement integer). - Example:
fun main(args : Array) ( val highestScore: Long = 9999 println("$highestScore") )
When you run the program, the output will be:
9999
If you assign an integer value greater than 231-1
or less than -231
to a variable (without explicitly specifying its type), the variable will be of Long
type. For example,
val distance = 10000000000 // distance variable of type Long
Similarly, you can use capital letter L to specify that the variable is of type Long
. For example,
val distance = 100L // distance value of type Long
5. Double
- The
Double
type is a double-precision 64-bit floating point. - Example:
fun main(args : Array) ( // distance is of type Double val distance = 999.5 println("$distance") )
When you run the program, the output will be:
999.5
Float
- The
Float
data type is a single-precision 32-bit floating point. Learn more about single precision and double precision floating point if you are interested. - Example:
fun main(args : Array) ( // distance is of type Float val distance = 19.5F println("$distance") )
When you run the program, the output will be:
19.5
Notice that, we have used 19.5F
instead of 19.5
in the above program. It is because 19.5
is a Double
literal, and you cannot assign Double
value to a variable of type Float
.
To tell compiler to treat 19.5
as Float
, you need to use F at the end.
If you are not sure what number value a variable will be assigned in the program, you can specify it as Number
type. This allows you to assign both integer and floating-point value to the variable (one at a time). For example:
fun main(args : Array) ( var test: Number = 12.2 println("$test") test = 12 // Int smart cast from Number println("$test") test = 120L // Long smart cast from Number println("$test") )
When you run the program, the output will be:
12.2 12 120
To learn more, visit: Kotlin smart casts
Char
To represent a character in Kotlin, Char types are used.
Unlike Java, Char types cannot be treated as numbers. Visit this page to learn more about Java char Type.
fun main(args : Array) ( val letter: Char letter = 'k' println("$letter") )
When you run the program, the output will be:
k
In Java, you can do something like:
char letter = 65;
However, the following code gives error in Kotlin.
var letter: Char = 65 // Error
Boolean
- The
Boolean
data type has two possible values, eithertrue
orfalse
. - Example:
fun main(args : Array) ( val flag = true println("$flag") )
Booleans are used in decision making statements (will be discussed in later chapter).
Kotlin Arrays
Masyvas yra talpykla, kurioje yra vieno tipo duomenys (reikšmės). Pvz., Galite sukurti masyvą, kuriame gali būti 100 Int
tipo reikšmių .
Kotlinas masyvus atstovauja Array
klasė. Klasė turi get
ir set
funkcijas, size
nuosavybę ir dar keletą naudingų narių funkcijų.
Norėdami sužinoti išsamiau apie masyvus, apsilankykite: Kotlin Arrays
Kotlino stygos
Kotline stygas atstoja String
klasė. Styginiai literalai, tokie kaip „tai yra eilutė“, yra įgyvendinami kaip šios klasės egzempliorius.
Norėdami išsamiai sužinoti apie stygas, apsilankykite: Kotlin Strings
Rekomenduojami skaitiniai
- Tipo konversija Kotline
- Protingi aktoriai Kotline
- „Kotlin“ niekiniai tipai