Skip to content

Declaring Variables

Rajesh Khadka edited this page Apr 20, 2019 · 2 revisions

Var

Declaration

var name: String = "Bob" or var name = "Bob"
var age:Int = 23 or var age = 23

Data type in kotlin is optional. Kotlin infers data type itself according to value assigned to it unlike java.

Val

Val is immutable. Once the value of val is assigned it can not be altered later. It is the same as the final keyword in java. It will be inferred in runtime. We don't have to assign a value at compile time.

Declaration

val salary = 1000

Constants

Declaration

const val LANGUAGE="en"

If you have the value of type string or primitive data which is known at compile time then you can declare as const. const can be declared at the top of the file or inside object declaration.

  1. Top of the file Util.kt
const val locale = "en"
  1. Inside Object declaration
object Utils{
    const val locale = "en"
}

Variable naming convention

lowerCamelCase example priceRange, profileCount, personalInformation In general, identifiers may consist of letters, digits, and underscores, and may not begin with a digit.

Use all capital letters for constant

const val MAX_PER_COUNT=100

Best practices for Variable naming

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Martin Fowler

The code should tell the story while going through it. It should be like good poetry or story which is easily relatable by the user.

The variable naming convention is wholly dependent upon many factors like a programming language, programmer's native language, limitations in hardware, software, and time constraints.

Do's & Don't

Description Don't Do's
Use Intention Revealing names var d:Int var elapsedTimeInDays:Int
Use pronounceable names var genymdhms:Date
var modymdhms:Date
var generationTimestamp:Date
var modificationTimestamp:Date
Use searchable names sum = (item*4)/5 const val WORK_DAYS_PER_WEEK = 5
val realDaysPerIdealDay = 4
sum = (item * realDaysPerIdealDay)/ WORK_DAYS_PER_WEEK

References

  1. https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c
  2. https://dzone.com/articles/best-practices-variable-and