Variabili di Kotlin e tipi di base

In questo tutorial imparerai a conoscere le variabili, come crearle e i tipi di dati di base che Kotlin supporta per la creazione di variabili.

Come sapete, una variabile è una posizione nella memoria (area di archiviazione) per contenere i dati.

Per indicare l'area di archiviazione, a ciascuna variabile dovrebbe essere assegnato un nome univoco (identificatore). Ulteriori informazioni su Come denominare una variabile in Kotlin?

Come dichiarare una variabile in Kotlin?

Per dichiarare una variabile in Kotlin, viene utilizzata la parola chiave varo val. Ecco un esempio:

 var language = "French" val score = 95

La differenza nell'utilizzo di var e val è discussa più avanti nell'articolo. Per ora, concentriamoci sulla dichiarazione delle variabili.

In questo caso, la lingua è una variabile di tipo Stringed scoreè una variabile di tipo Int. Non è necessario specificare il tipo di variabili; Kotlin lo fa implicitamente per te. Il compilatore lo sa dall'espressione dell'inizializzatore ("French" è a Stringe 95 è un valore intero nel programma precedente). Questa è chiamata inferenza del tipo nella programmazione.

Tuttavia, puoi specificare esplicitamente il tipo se desideri:

 var language: String = "French" val score: Int = 95

Abbiamo inizializzato la variabile durante la dichiarazione negli esempi precedenti. Tuttavia, non è necessario. È possibile dichiarare la variabile e specificarne il tipo in un'istruzione e inizializzare la variabile in un'altra istruzione più avanti nel programma.

 var language: String // dichiarazione di variabile di tipo String … language = "French" // inizializzazione di variabile val score: Int // dichiarazione di variabile di tipo Int … score = 95 // inizializzazione di variabile 

Di seguito sono riportati alcuni esempi che risultano in errore.

 var language // Error language = "French"

Qui, il tipo di variabile del linguaggio non è specificato esplicitamente, né la variabile viene inizializzata durante la dichiarazione.

 var language: String language = 14 // Errore

Qui, stiamo cercando di assegnare 14 (valore intero) a una variabile di tipo diverso ( String).

Differenza tra var e val

  • val (Riferimento immutabile) - La variabile dichiarata utilizzando la valparola chiave non può essere modificata una volta assegnato il valore. È simile alla variabile finale in Java.
  • var (Riferimento mutabile) - La variabile dichiarata utilizzando la varparola chiave può essere modificata successivamente nel programma. Corrisponde alla normale variabile Java.

Alcuni esempi:

 var language = "French" language = "German" 

Qui, la languagevariabile viene riassegnata al tedesco. Poiché la variabile viene dichiarata utilizzando var, questo codice funziona perfettamente.

 val language = "French" language = "German" // Errore

Non è possibile riassegnare la variabile di lingua a Germannell'esempio precedente perché la variabile è dichiarata utilizzando val.

Ora, sai cosa sono le variabili di Kotlin, è tempo di imparare diversi valori che una variabile di Kotlin può assumere.

Tipi di base di Kotlin

Kotlin è un linguaggio tipizzato staticamente come Java. Cioè, il tipo di una variabile è noto durante la fase di compilazione. Per esempio,

 val language: Int val mark = 12.3

Qui, il compilatore sa che la lingua è di tipo Inte i contrassegni sono di tipo Doubleprima della compilazione.

I tipi incorporati in Kotlin possono essere classificati come:

  • Numeri
  • Personaggi
  • Booleani
  • Arrays

Tipo di numero

I numeri in Kotlin sono simili a Java. Ci sono 6 tipi incorporati che rappresentano i numeri.

  • Byte
  • Corto
  • Int
  • Lungo
  • Galleggiante
  • Doppio

1. Byte

  • Il Bytetipo di dati può avere valori da -128 a 127 (intero con complemento a due con segno a 8 bit).
  • 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 to 231-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 to 263-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, either true or false.
  • 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

Un array è un contenitore che contiene dati (valori) di un unico tipo. Ad esempio, puoi creare un array che può contenere 100 valori di Inttipo.

In Kotlin, gli array sono rappresentati dalla Arrayclasse. La classe ha gete setfunzioni, sizeproprietà e poche altre utili funzioni membro.

Per informazioni dettagliate sugli array, visitare: Kotlin Arrays

Kotlin Strings

In Kotlin, le stringhe sono rappresentate dalla Stringclasse. I letterali stringa come "questa è una stringa" sono implementati come istanza di questa classe.

Per conoscere in dettaglio le corde, visita: Kotlin Strings

Letture consigliate

  • Digitare la conversione in Kotlin
  • Cast intelligenti a Kotlin
  • Tipi nullable di Kotlin

Articoli interessanti...