Jumping from any Language (Java) to Kotlin
Hey friends! Stopping my Java series for a while due to some projects going on in my college. As this blog should contain all those concepts which I learn, that's why I am creating this blog. Actually this is about Android Development through Kotlin, so I will here write for anyone who is known to any other language can easily move to Kotlin (Those who are new to programming should ignore this blog completely!)
Functions in Kotlin
// fun_functionname(){}
fun firstFunction(){
}
// for any function which want to return something
fun secondFunction(): Int{
return 0
}
// function taking arguments
fun thirdFunction(name: String, age: Int): Int{
return age
}
Printing in Kotlin
print("Hello World")
val and var in Kotlin
val and var are that data types which can be assigned as integer, float, string or anything you want! The difference between val and var is just that you can't reassign val but can do this with var!
fun firstFunction(){
val str1="Hello World"
var str2="Manik"
print(str1+" "+str2)
// you can't do this!
str1="Hello Universe"
//you can do this!
str2="Your Name Please!"
}
Constraining val and var
As I said that val and var can be assigned by any data type but what if someone wants to constraint it to some data type, take example that I need val that should always be a byte. What would I do? I would use colon (:)
fun firstFunction(){
val myByte: Byte=12
//this is not allowed
val myByte1: Byte=123456
}
Colon would ensure that val is of type Byte only. Colon is used widely for other purposes also, we would learn it later!
String
Basically, string is stored as an array of characters. See this!
fun firstFunction(){
val str1="Hello World"
val char=str1[0]
// Strings can also be interpolated as
print("Say $str1 three times!")
//This wouldn't give the desired output
print("The length of str1 is: $str1.length")
// Output would be: The length of str1 is Hello World.length
// But this would give the desired output
print("The length of str1 is: ${str1.length}")
}
When
When is also similar to if-else It has the same meaning in Kotlin as in English. Different cases are shown by "->" sign. See this code
var num=3
when(num){
1-> print("The value of num is 11")
2-> print("The value of num is 28")
3-> print("The value of num is 35")
else-> print("Invalid input")
// output will be The value of num is 35
}
"in" keyword is also used in these conditions for taking a range as an option. For example if you want to take range of 1 to 3 then you would write "in 1..3-> condition". You can also use commas if you want particular inputs giving same outputs (for example if we want same conditions for 1,3,8 then we would write "1,3,8->condition)
Is
Is just checks whether the given variable is int, float, string or anything else. See this code:
var anything: Any=25;
// here Any is just an object which can be assigned by any data type
when(anything){
is int-> print("This is an integer")
is String-> print("This is a String")
else -> print("Don't know!")
Not is "!is"
Question Mark Operator
The very first point to be noted is that you can't assign any variable in Kotlin as "null" and if you want to assign any var/val as null then you need to use question mark operator
// not allowed
var str1: String=null
// allowed
var str2: String?=null
You can't calculate length of str2 by str2.length but by using question mark operator you can do that(str2?.length and str2? can't be null, if it is null it will give compilation error there itself). Basically, question mark operator tells the compiler that str2 can be null and using that operator again it confirms that it is not null!
Let's understand it deeply!
var str1: String?="Manik"
var str2: String= str1?:"Hi!"
/* Here question mark operator tells the compiler that str1 can be null, now you can't directly assign str1 to str2 as str2 is just a String that is it can't be null, so for that you need to consider that case also in which str1 would be null and st1?:"Hi" says that if str1 us null then assign it Hi. Basically question mark operator just tells the compiler that data type can't be null so that if it is null in future then compiler could stop it immediately and is not passed to the app user!*/
Classes
Classes have same concept as in Java or any other language, we can declare a class in kotlin in following way:
// class with default constructor
class firstClass{
}
// class with public constructor
class secondClass(name: String, age:Int){
}
// class with private constructor
class thirdClass private constructor(name: String, age: Int){
}
Objects
The syntax for object creation is very easy to understand, just see this:
val obj1: firstClass= firstClass()
val obj2: secondClass= secondClass("Manik",25)
val obj3: thirdClass= thirdClass("Manik",25)
Init
Init is the static block of Kotlin, if you want to initialize something on the creation of an object then we use init, syntax is as follows
class letssay{
init{
// body of what you want to initialize
}
}
Getter and Setter
Kotlin always works in form of getter and setter, even when you are not declaring any getter or setter, kotlin use them. This means, Kotlin already define this
class kotlingetter(){
val myName: String="Manik"
// this is already defined by kotlin
get(){
return field
}
set(value){
value=field
}
But for sure you can customize getter and setter in this way
class gettersetter (){
val CarName: String="BMW"
get(){
return field.toLowerCase() //here we have made a custom getter so that whenever any property of this class is accessed, this getter is used, field denotes the property of this variable or we can say it stores the variable for which getter and setter is made (field is already defined by Kotlin) You can use this getter without using get() function!
}
val CarSpeed: Int=250
set(value){
field=if(value>120) print("Warning") else print("Ok!")
// Value is also defined by Kotlin which takes the value of the variable for which getter and setter is defined, here value=CarSpeed=250>120, hence Warning will be printed
}
val obj1: gettersetter= gettersetter()
print(obj1.CarName) // BMW will be printed in lower case!
Customized getter and setter should be declared directly under the property you want to customize! The following code will make things more clear!
class gettersetter (){
val CarName: String="BMW"
get(){
return field.toLowerCase() //here we have made a custom getter so that
// whenever any property of this class is accessed, this getter is used, field denotes the property of this variable or we can say it stores the variable for which getter and setter is made (field is already defined by Kotlin) You can use this getter without using get() function!
}
val CarSpeed: Int=250
set(value){
field=if(value>120) print("Warning") else print("Ok!")
// Value is also defined by Kotlin which takes the value of the variable for which getter and setter is defined, here value=CarSpeed=250>120, hence Warning will be printed
val CarInternal: Any=29
private set // this will make the setter private, hence make the val private
}
val obj1: gettersetter= gettersetter()
print(obj1.CarName) // BMW will be printed in lower case!
So the most important thing to remember is that you don't need to invoke getter and setter in Kotlin and getter and setter should be declared directly under the property you want to customize!
Inheritence
A class should be declared "open" for inheritance.
A sub-class can be inherited by using colon, that means, class subclassName: parentClassName(){}
All the concepts of Inheritence, Polymorphism and Abstract Classes are similar to Java which is already present in this blog, you can check it!
Interface
The concept, declaration and working of Interfaces is same as Java, you can check it on the blog. Even you haven't coded in Java ever but have command on any other language you can read Interfaces Blog, you will understand it properly but the condition is that your concept of interfaces in that language should be clear because the minimum eligibility of this blog is that you should we well acquainted with any one language.
Arrays
Arrays are very basic elements of any language. The syntax is given below:
val num: IntArray=intArrayof(1,2,3,4,5) // array of integers
val num1=intArrayof(1,2,3,4,5,6) // array of integers
// printing array: Although we can print an array using for loop but here is an altenative way
print(num.contenttoString())
// this will print the array: [1,2,3,4,5]
// in keyword
// in keyword has same meaning as that in English language
// let's say a variable x, so for printing array we can write
for(x in num){ // this means for x as an element in num array, print x
print(x) // this will print array
}
// an array of any type
val arr=arrayOf("Hello", 1,1.56,'c')
So, that's it from my side for Kotlin, not all the concepts are covered here but I think the concepts covered in this blog are enough for you to start Android development in Kotlin. Bye-Bye!