Subscribe for notification
Categories: Android Tutorial

How to Declare and Use Variables in Kotlin

There are two types of variables in Kotlin: read-only and mutable. Read-only variables (or constants) are declared with val and mutable with var. Every variable must be declared. Any attempt to use a variable that hasn’t been declared yet is a syntax error; thus, you are protected from accidentally assigning to a misspelled variable. The declaration also decides what kind of data you are allowed to store in the variable.

Local variables are typically declared and initialized at the same time, in which case the type of the variable is inferred to be the type of the expression you initialize it with. Int is a type that represents an integer, one of the many numerical types that can be represented in Kotlin. Similar to other languages, you can also use Byte, Short, Long, Float, and Double depending on your numerical data.

A variable refers to a memory location that stores some data. It has a name and an associated type. The type of a variable defines the range of values that the variable can hold, and the operations that can be done on those values. Although Kotlin is a statically typed language, It doesn’t require you to explicitly specify the type of every variable you declare. It can infer the type of a variable from the initializer expression.

An interesting thing from Kotlin is that most of the time you won’t need to specify the type of the objects you are working with, as long as the compiler can infer it. So we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly.

Sponsored
SyncSaS

SyncSaS Technologies is specialized in creating and designing customized software. We have our own team that will be in charge of developing your softwares.

Share
Published by

Recent Posts

Adsense Updated Dashboard

Changes in Adsense Dashboard Recently you might have seen few changes in Adsense dashboard, these…

3 weeks ago

Guide Book For Google Adsense

With my experience in working as AdSense publisher, I have written many articles, tutorials for…

3 weeks ago

How to manage Google Adsense to get High CPC

Manage Adsense for High CPC CPC (Cost per click) in simple words the CPC is…

3 weeks ago

Google Adsense Introduce page level ads

If you are already the publisher of Google Adsense account then now its time to…

3 weeks ago