Dalam tutorial ini, Anda akan belajar tentang variabel, cara membuatnya, dan tipe data dasar yang didukung Kotlin untuk membuat variabel.
Seperti yang Anda ketahui, variabel adalah lokasi di memori (tempat penyimpanan) untuk menyimpan data.
Untuk menunjukkan tempat penyimpanan, setiap variabel harus diberi nama unik (pengenal). Pelajari lebih lanjut tentang Bagaimana memberi nama variabel di Kotlin?
Bagaimana cara mendeklarasikan variabel di Kotlin?
Untuk mendeklarasikan variabel di Kotlin, var
atau val
kata kunci digunakan. Berikut ini contohnya:
var language = skor val "Prancis" = 95
Perbedaan dalam menggunakan var dan val dibahas nanti di artikel. Untuk saat ini, mari fokus pada deklarasi variabel.
Di sini, bahasa adalah variabel jenis String
, dan score
jenis variabel Int
. Anda tidak perlu menentukan jenis variabel; Kotlin secara implisit melakukan itu untuk Anda. Kompilator mengetahui hal ini dengan ekspresi penginisialisasi ("French" adalah a String
, dan 95 adalah nilai integer dalam program di atas). Ini disebut inferensi tipe dalam pemrograman.
Namun, Anda dapat secara eksplisit menentukan jenisnya jika Anda ingin:
bahasa var: String = "Prancis" skor val: Int = 95
Kami telah menginisialisasi variabel selama deklarasi dalam contoh di atas. Namun, itu tidak perlu. Anda dapat mendeklarasikan variabel dan menentukan jenisnya dalam satu pernyataan, dan menginisialisasi variabel di pernyataan lain nanti dalam program.
var language: String // deklarasi variabel tipe String… language = "French" // variabel inisialisasi skor val: Int // deklarasi variabel tipe Int… score = 95 // inisialisasi variabel
Berikut beberapa contoh yang menyebabkan kesalahan.
var language // Error language = "Prancis"
Di sini, jenis variabel bahasa tidak ditentukan secara eksplisit, atau variabel diinisialisasi selama deklarasi.
var language: String language = 14 // Error
Di sini, kami mencoba untuk menetapkan 14 (nilai integer) ke variabel tipe yang berbeda ( String
).
Perbedaan antara var dan val
- val (Referensi tetap) - Variabel yang dideklarasikan menggunakan
val
kata kunci tidak dapat diubah setelah nilainya ditetapkan. Ini mirip dengan variabel final di Java. - var (Referensi yang
var
dapat diubah ) - Variabel yang dideklarasikan menggunakan kata kunci dapat diubah nanti dalam program. Ini sesuai dengan variabel Java biasa.
Berikut beberapa contohnya:
var language = "Prancis" language = "Jerman"
Di sini, language
variabel dipindahkan ke bahasa Jerman. Karena, variabel dideklarasikan menggunakan var
, kode ini bekerja dengan sempurna.
val language = "French" language = "German" // Kesalahan
Anda tidak dapat menetapkan ulang variabel bahasa ke German
dalam contoh di atas karena variabel tersebut dideklarasikan menggunakan val
.
Sekarang, Anda telah mengetahui apa itu variabel Kotlin, saatnya mempelajari nilai-nilai berbeda yang dapat diambil variabel Kotlin.
Jenis Dasar Kotlin
Kotlin adalah bahasa yang diketik secara statis seperti Java. Artinya, jenis variabel diketahui selama waktu kompilasi. Sebagai contoh,
bahasa val: Int val mark = 12.3
Di sini, kompilator mengetahui bahwa bahasa itu bertipe Int
, dan tanda bertipe Double
sebelum waktu kompilasi.
Jenis bawaan di Kotlin dapat dikategorikan sebagai:
- Angka
- Karakter
- Boolean
- Array
Jenis Nomor
Angka di Kotlin mirip dengan Java. Ada 6 tipe bawaan yang mewakili angka.
- Byte
- Pendek
- Int
- Panjang
- Mengapung
- Dua kali lipat
1. Byte
- The
Byte
tipe data dapat memiliki nilai dari -128 ke 127 (8-bit menandatangani dua ini bilangan bulat pelengkap). - 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
Array adalah wadah yang menyimpan data (nilai) dari satu jenis tunggal. Misalnya, Anda dapat membuat larik yang dapat menampung 100 nilai Int
tipe.
Di Kotlin, array diwakili oleh Array
kelas. Kelas memiliki get
dan set
fungsi, size
properti, dan beberapa fungsi anggota lain yang berguna.
Untuk mempelajari secara detail tentang array, kunjungi: Kotlin Arrays
Kotlin Strings
Di Kotlin, string diwakili oleh String
kelas. Literal string seperti "ini adalah string" diimplementasikan sebagai turunan dari kelas ini.
Untuk mempelajari string secara mendetail, kunjungi: Kotlin Strings
Bacaan yang Direkomendasikan
- Ketik konversi di Kotlin
- Pemain pintar di Kotlin
- Jenis Kotlin nullable