Classes in Kotlin are declared using the keyword class{: .keyword }:
class Address { }
The class declaration consists of :
·Class name.
·Class header.(optional)
·Class body (surrounded by curly braces).(oprtional)
Both the header and the body are optional; if the class has no body, curly braces can be omitted.
class Address
2)Constructors :
Kotlin have two types of constructors.
1)Primary constructor :
The primary constructor is part of the class header: it is used after the class name.
class Placeconstructor(firstName:String) { }
constructor keyword can be omitted if constructor does not have any annotations or visibility modifiers.
class Place(placeName:String) { }
Primary constructor cannot contain any codeand Initialization code can be placed in initializer blocks.
class Employee(name:String) {
init {
logger.info("Employee initialized with value ${name}")
}
}
I
f the constructor has annotations or visibility modifiers, the constructor{: .keyword } keyword is required, and the modifiers go before it:
class Employeepublic @Injectconstructor(name:String) { ... }
2)Secondary constructor :
Used inside class which are prefixed with constructor{: .keyword }:
class Employee {
constructor(parent: Employee)
{
parent.children.add(this)
}
}
If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this{: .keyword } keyword:
Kotlin doesn not have “new” keyword for creating object. Objects are created as shown below:
valemployee= Employee()
valstudent= Student("Joe Smith")
Some examples on class and objects :
Example1 : Java code :
class Student{
int id;//field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Kotlin Code :
class Student { var id:Int = 0//field or data member or instance variable var name:String companion object { @JvmStatic fun main(args:Array<String>) { val s1 = Student()//creating an object of Student println(s1.id)//accessing member through reference variable println(s1.name) } } }
In this tutorial we will learn how to declare variables in Kotlin. We are having java comparison code for easy and quick learning.
In kotlin all data types are defined with keyword var. There is no final
Example 1 :
Java Code :
class A{ private int data=50; public String mData = "Test"; procted float test1 = 1.23; private double test2 = 2.33; //instance variable public static final int FILES_TO_DOWNLOAD = 100 //static variable
void method(){ int n=90;//local variable } }//end of class
Converted Kotlin Code :
class A { private val data = 50 var mData = "Test" var test1 = 1.23f private val test2 = 2.33//instance variable fun method() { val n = 90//local variable } companion object { val FILES_TO_DOWNLOAD = 100//static variable } }//end of class
varscore=// some scorevargrade=when (score) {
9, 10->"Excellent"in6..8->"Good"4, 5->"Ok"in1..3->"Fail"else->"Fail"
}
Java
for (int i =1; i <=10 ; i++) { }
for (int i =1; i <10 ; i++) { }
for (int i =10; i >=0 ; i--) { }
for (int i =1; i <=10 ; i+=2) { }
for (int i =10; i >=0 ; i-=2) { }
for (String item : collection) { }
for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in1..10) { }
for (i in1 until 10) { }
for (i in10 downTo 0) { }
for (i in1..10 step 2) { }
for (i in10 downTo 1 step 2) { }
for (item in collection) { }
for ((key, value) in map) { }
void doSomething(int... numbers) {
// logic here
}
Kotlin
fundoSomething(varargnumbers:Int) {
// logic here
}
Java
int getScore() {
// logic herereturn score;
}
Kotlin
fungetScore():Int {
// logic herereturn score
}
// as a single-expression functionfungetScore():Int= score
Java
int getScore(int value) {
// logic herereturn2* value;
}
Kotlin
fungetScore(value:Int):Int {
// logic herereturn2* value
}
// as a single-expression functionfungetScore(value:Int):Int=2* value
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticintgetScore(intvalue) {
return2* value;
}
}
Kotlin
class Utilsprivateconstructor() {
companion object {
fungetScore(value:Int):Int {
return2* value
}
}
}
// other way is also there
object Utils {
fungetScore(value:Int):Int {
return2* value
}
}
Java
publicclassDeveloper {
privateString name;
privateint age;
publicDeveloper(Stringname, intage) {
this.name = name;
this.age = age;
}
publicStringgetName() {
return name;
}
publicvoidsetName(Stringname) {
this.name = name;
}
publicintgetAge() {
return age;
}
publicvoidsetAge(intage) {
this.age = age;
}
@Overridepublicbooleanequals(Objecto) {
if (this== o) returntrue;
if (o ==null|| getClass() != o.getClass()) returnfalse;
Developer developer = (Developer) o;
if (age != developer.age) returnfalse;
return name !=null? name.equals(developer.name) : developer.name ==null;
}
@OverridepublicinthashCode() {
int result = name !=null? name.hashCode() :0;
result =31* result + age;
return result;
}
@OverridepublicStringtoString() {
return"Developer{"+"name='"+ name +'\''+", age="+ age +'}';
}
}
Kotlin
data class Developer(varname:String, varage:Int)
Java
publicclassUtils {
privateUtils() {
// This utility class is not publicly instantiable
}
publicstaticinttriple(intvalue) {
return3* value;
}
}
int result =Utils.triple(3);
Kotlin
fun Int.triple():Int {
returnthis*3
}
varresult=3.triple()