When over Switch in Kotlin
Good afternoon Programming Community, I am glad to welcome you to another Kotlin edition. we will look upon the replacement of switch with the when keyword. Firstly, we will look on to some examples of switch and after that, we will look at how the when keyword makes our task or code easier and more understandable. So, let’s get started.
Standard Conditional
if (number == 1) {
println("value: 1")
} else if (nummber == 2) {
println("value: 2")
} else if (number == 3) {
println("value: 3")
} else if (number == 4) {
println("value 4")
} else {
println("value greater 5")
}
A traditional switch is basically just a statement that can substitute a series of simple if/else that make basic checks as displayed above. However it cannot replace all sort of if/else sequences but just those which compare a value with some constant. So, you can only use a switch to perform an action when one specific variable has a certain precise value.
To remove this difficulty, switch-case was introduced, where we pass the variable to be compared with-in the switch statement (in our example, that variable is number) and compare it with various case statements present corresponding to it and do the operation.
‘switch’
switch (number) {
case 1:
println("value: 1")
break;
case 2:
println("value: 2")
break;
case 3:
println("value: 3")
break;
case 4:
println("value: 4")
break;
default:
println("value greater 5")
break;
}
So, in the above code in order to print the numbers in word, you have to use various conditional statements and this results in a large number of lines of code. Think of a situation when you have to print the words representation of numbers up to 100 or 1000. If you are using conditional statements then you have to use 1000 conditional statements.
In the above code, number is passed in switch statement and cases are used to compare that number. For example, if the number is 1 then case 1 will be executed, if number is 2 then case 2 will be executed and so on. But if the number is not equal to any of the case present then the default block will be executed.
‘when’
when {
number == 1 -> {
println("value: 1")
}
nummber == 2 -> {
println("value: 2")
}
number == 3 -> {
println("value: 3")
}
number == 4 -> {
println("value 4")
}
else -> {
println("value greater 5")
}
}
So, if you are moving from Java to Kotlin, then you will find some changes in the syntax part also. In Java we use switch but in Kotlin, that switch gets converted to when. when is also used for conditional representation but it does the things in a very smarter and easier way. Whenever you are having a number of possibilities then you can use when in your code.
In the above code, like in switch, the number is passed in when and then we compare that number with various options available. In our case, if the number == 1, then “one” will be printed and so on. If more than one match is found then the match that occurs first will be considered only. If no match to the number is found then the else part will be executed.
When in doubt use ‘when’
- no complex case/break groups, only the condition followed by ->
- it can group two or more equivalent choices, separating them with a comma
Wrapping Things Up
we learned how to use when in place of switch in Kotlin. We saw that, if we are having a number of possibilities for a particular variable then we can make use of when to handle all the possibilities. Also, we can use when for multiple or more than one choices.
- Published in Android, Kotlin, Programming Languages
Val vs Var
Any programming language a variable is referred to a location in memory(storage area) to stored data. The type of variable defines the range of value that the variable can hold. So indicate a storage space, each variable should be given a unique identifier.
Basically, val and var both are used to declare a variable. var is like a general variable and can be assigned multiple times and is known as the mutable variable in Kotlin. Whereas val is a constant variable and can not be assigned multiple times and can be Initialized only single time and is known as the immutable variable in Kotlin.
Declaring a variable in Kotlin
Var
is short for variable – The object stored in the variable could change (vary) in time.
private val adapter: HomeAdapter? = null
After the Initialized It will not throw me an error because var is a mutable and it can be assigned multiple times.
Val
is short for value – The object stored in val, could not vary in time. Once assigned the val becomes read only, like a constant in Java Programming language.
private var adapter: HomeAdapter? = null
After the Initialized It will throw me an error like “Val can not be reassigned”
So to conclude we have learnt about Val vs Var in Kotlin that var could be changed at any level. Whereas val once assigned, could not be changed, but its properties could be changed.
- Published in Android, Kotlin, Programming Languages, Uncategorized
Android w/ Fragments
A fragment is an Android component that holds part of the behavior and/or UI of an activity. As the name would suggest, fragments are not independent entities, but are tied to a single activity. In many ways, they have functionality similar to activities.
In the same way that you don’t actually need an army of little helpers to do your bidding, you don’t have to use fragments. However, if you use them well, they can provide:
- Modularity – Diving complex activity code across fragments for better maintenance
- Adaptability – representing sections of a UI within the different fragments while utilizing different layouts that relys on the screen orientation and size
- Reusability – placing behavior or UI parts within the fragments that multiple activities can share
Fragment Lifecycle of Android
As you already know like activity, a fragment has a lifecycle with events that occur when the status changes within the framents. For example, when an event fires becasue a fragment becomes visible and active, or is not used or removed. Just as in a regular activity you are able to add code and behavior to the callbacks for the events.
Below you will see the fragment lifescycle diagram:

Understanding the lifecycle
- onAttach : the fragment attaches to its host activity
- onCreate : When a new fragment initializes, which always happens after it attaches to the hosts.
- onCreateView : creates its portion of the view hierarchy, which then added to the activity’s hierarchy of view
- onActivityCreated : fragment’s activity has finished on its own onCreate
- onStart : fragment becomes visible and starts after its activity starts
- onResume : fragment is visible and interactable that resumes only after its activity resumes and often resumes immediately after the activity does.
- onPause : user may not interact
- onStop : this is fired when the fragment is no longer visible; the fragment will get change with another fragment or it gets removed from actvity or fragment’s is stopped
- onDestroyView : this is fired when the view and other resources created within the onCreateView() are removed from the activity’s view hierarchy and destroyed.
- onDestroy : fired when the fragment does the final clean up.
- onDetach : fires when the fragment is detached from the activity host
If you want to learn more details regarding please read “Droid Fragments Life”.This is all about how the fragment come up within the activity and goes out. Cool!!
- Published in Android, Java, Kotlin, Programming Languages
Java Or Kotlin Language: Deciding Which Option to Use for Android Development
If my math is not wrong Java has been around for over 20+ years now and has no intention of going away. It holds a supreme position in the list of most popular programming languages following the C and C++ =, setting the highest usability record with millions of developers and systems.
Random Fact:
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language back in 1991. Java has been the primary language for Android app development along with a few of its companions: Scala, Groovy and stepping up is Kotlin.
Kotlin Background
Let first you will need to understand what exactly is Kotlin so it is considered as statically typed programming language that runs on JVM(Java Virtual Machine) and JavaScript. It is developed by JetBrains and open-source community. The ‘Kotlin’ name came from Kotlin Island located near Saint Petersburg. It is supported by leading IDEs and compatible with Java 6 or Java 8. Kotlin is described as a general-purpose language and introduces functional features to support Java interoperability. The Kotlin project was born out of the aspiration for heightened productivity. The goal was to improve the coding experience in a way that was both practical and effective.
A central focus of Kotlin is to enable mixed-language projects. Kotlin also introduces improved syntax, as well as concise expressions and abstractions. Using Kotlin with Java reduces excessive boilerplate code, which is a huge win for Android developers. Kotlin came when Android development needed a more modern language to add to the qualities of java and aid in mobile development. This allows developers to not only easily update old Java apps to Kotlin, but also carry on their old work in Java to Kotlin.
Here’s a brief example Kotlin language
package hello
fun main() {
println("Hello World")
}
It’s that simple! Kotlin uses developer-friendly coding structures and norms that are easy-to-understand and use. When considering this example from the develops’ perspective, you will be able to understand why Kotlin is loved by developers around the world. It is concise, effective, and faster compared to Java.
Is Java Dead?
Based on the group that I program with it appears that Java is currently in the area with us developers. Java is a reputable programming language with vast open-source tools and libraries to help developers. With that said, no language is without fault and even Java is subject to complications that can make a developer’s job tedious. If anything the objective for Kotlin is to supposedly introduce solutions to the common programming headaches and improve the Java ecosystem as a whole.
Strict Trial And Error
Kotlin has some milage under itself and has become a more stable and congruous development option especially within the Android Studio IDE. Some developers seem to believe that Kotlin will oust Java for Android development in future years. Other reviewers seem to believe Kotlin and Java should be coexisting without one outweighing the other.
This is a quality Java is not known for; however, readability should always take priority over concision. Yes, the succinct nature of Kotlin simplifies a developer’s job and mitigates the risk for error, but Kotlin doesn’t practice concision for concision’s sake. So let’s take the example below and compare the difference in the languages presents.
public class MathLife {
public static double calculate () throws Exception {
switch(op) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return a / b;
default:
throw new Exception();
}
}
}
Above is a simple calculator function written in Java. For comparison, here is the same calculator in Kotlin:
fun calculate(a: Double, op: String, b: Double): Double {
when (op) {
"add" -> return a + b
"subtract" -> return a - b
"multiply" -> return a * b
"divide" -> return a / b
else -> throw Exception()
}
}
It may not seem like much, but the Kotlin version of this calculator is written in half the lines of code it took to program the function in Java. Brevity is a crucial factor in productivity. Writing large projects becomes easier when a developer is given more power for every line of code. A key observation here is Kotlin does not overlook comprehension for the sake of brevity. The syntax is concise, readable and still substantial.
The Winner: Java or Kotlin
In all fairness, chances are that you have been taught, learn and embraced Java. Switching to Kotlin at a time can be a bit of shock, so it is important to do this transition slowly to make sure you understand. having said that, Kotlin is the new official language and owing to its modern nature, it will become widely adopted in the future, so learning it and starting development with it right now would be a good idea. Understand java will continue to be a popular language for several years to come and isn’t likely to be entirely replaced. So take your time and make the switch gently.
At the end of the day, it’s all about what you feel comfortable with. As stated previously to be a true blood Androidian, you will need to have a working knowledge of the language Java. But if you already do have that then the Kotlin language of the future, so you might as well spend some time getting accustomed to it.
- Published in Android, Java, Kotlin, Language, Programming Languages
- 1
- 2










