Java To Kotlin PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Java To Kotlin

Print to Console
Java
1 System.out.print("Amit Shekhar");
2 System.out.println("Amit Shekhar");
Kotlin
1 print("Amit Shekhar")
2 println("Amit Shekhar")
 

Constants and Variables


Java
1 String name = "Amit Shekhar";
2 final String name = "Amit Shekhar";
Kotlin
1 var name = "Amit Shekhar"
2 val name = "Amit Shekhar"
 

Assigning the null value


Java
1 String otherName;
2 otherName = null;
Kotlin
1 var otherName : String?
2 otherName = null
 
Verify if value is null
Java
1 if (text != null) {
2   int length = text.length();
3 }
Kotlin
1 text?.let {
2     val length = text.length
3 }
4 // or simply
5 val length = text?.length
 

Concatenation of strings
Java
1 String firstName = "Amit";
2 String lastName = "Shekhar";
3 String message = "My name is: " + firstName + " " + lastName;
Kotlin
1 var firstName = "Amit"
2 var lastName = "Shekhar"
3 var message = "My name is: $firstName $lastName"
 

New line in string


Java
1 String text = "First Line\n" +
2               "Second Line\n" +
3               "Third Line";
Kotlin
1 val text = """
2         |First Line
3         |Second Line
4         |Third Line
5         """.trimMargin()
 

Ternary Operations
Java
1 String text = x > 5 ? "x > 5" : "x <= 5";
2

3 String message = null;


4 log(message != null ? message : "");
Kotlin
1 val text = if (x > 5)
2               "x > 5"
3            else "x <= 5"
4

5 val message: String? = null


6 log(message ?: "")
 

Bitwise Operators
Java
1 final int andResult  = a & b;
2 final int orResult   = a | b;
3 final int xorResult  = a ^ b;
4 final int rightShift = a >> 2;
5 final int leftShift  = a << 2;
6 final int unsignedRightShift = a >>> 2;
Kotlin
1 val andResult  = a and b
2 val orResult   = a or b
3 val xorResult  = a xor b
4 val rightShift = a shr 2
5 val leftShift  = a shl 2
6 val unsignedRightShift = a ushr 2
 

Check the type and casting


Java
1 if (object instanceof Car) {
2 }
3 Car car = (Car) object;
Kotlin
1 if (object is Car) {
2 }
3 var car = object as Car
4

5 // if object is null
6 var car = object as? Car // var car = object as Car?
 

Check the type and casting (implicit)


Java
1 if (object instanceof Car) {
2    Car car = (Car) object;
3 }
Kotlin
1 if (object is Car) {
2    var car = object // smart casting
3 }
4

5 // if object is null
6 if (object is Car?) {
7    var car = object // smart casting, car will be null
8 }
 

Multiple conditions
Java
if (score >= 0 && score <= 300) { }
Kotlin
if (score in 0..300) { }
 

Multiple Conditions (Switch case)


Java
1 int score = // some score;
2 String grade;
3 switch (score) {
4     case 10:
5     case 9:
6         grade = "Excellent";
7         break;
8     case 8:
9     case 7:
10     case 6:
11         grade = "Good";
12         break;
13     case 5:
14     case 4:
15         grade = "OK";
16         break;
17     case 3:
18     case 2:
19     case 1:
20         grade = "Fail";
21         break;
22     default:
23         grade = "Fail";             
24 }
Kotlin
1 var score = // some score
2 var grade = when (score) {
3     9, 10 -> "Excellent"
4     in 6..8 -> "Good"
5     4, 5 -> "OK"
6     in 1..3 -> "Fail"
7     else -> "Fail"
8 }
 

For-loops
Java
1 for (int i = 1; i <= 10 ; i++) { }
2

3 for (int i = 1; i < 10 ; i++) { }


4

5 for (int i = 10; i >= 0 ; i--) { }


6

7 for (int i = 1; i <= 10 ; i+=2) { }


8

9 for (int i = 10; i >= 0 ; i-=2) { }


10

11 for (String item : collection) { }


12
13 for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
1 for (i in 1..10) { }
2

3 for (i in 1 until 10) { }


4

5 for (i in 10 downTo 0) { }
6

7 for (i in 1..10 step 2) { }


8

9 for (i in 10 downTo 0 step 2) { }


10

11 for (item in collection) { }


12

13 for ((key, value) in map) { }


 

Collections
Java
1 final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);
2

3 final Map<Integer, String> keyValue = new HashMap<Integer, Strin


g>();
4 map.put(1, "Amit");
5 map.put(2, "Ali");
6 map.put(3, "Mindorks");
7

8 // Java 9
9 final List<Integer> listOfNumber = List.of(1, 2, 3, 4);
10

11 final Map<Integer, String> keyValue = Map.of(1, "Amit",


12                                              2, "Ali",
13                                              3, "Mindorks");
Kotlin
1 val listOfNumber = listOf(1, 2, 3, 4)
2 val keyValue = mapOf(1 to "Amit",
3                      2 to "Ali",
4                      3 to "Mindorks")
 

for each
Java
1 // Java 7 and below
2 for (Car car : cars) {
3   System.out.println(car.speed);
4 }
5

6 // Java 8+
7 cars.forEach(car -> System.out.println(car.speed));
8

9 // Java 7 and below


10 for (Car car : cars) {
11   if (car.speed > 100) {
12     System.out.println(car.speed);
13   }
14 }
15

16 // Java 8+
17 cars.stream().filter(car -> car.speed > 100).forEach(car -> Syst
em.out.println(car.speed));
18 cars.parallelStream().filter(car -> car.speed > 100).forEach(car
-> System.out.println(car.speed));
Kotlin
1 cars.forEach {
2     println(it.speed)
3 }
4

5 cars.filter { it.speed > 100 }


6       .forEach { println(it.speed)}
7

8 // kotlin 1.1+
9 cars.stream().filter { it.speed > 100 }.forEach { println(it.spe
ed)}
10 cars.parallelStream().filter { it.speed > 100 }.forEach { printl
n(it.speed)}
 

Splitting arrays
java
1 String[] splits = "param=car".split("=");
2 String param = splits[0];
3 String value = splits[1];
kotlin
val (param, value) = "param=car".split("=")
 

Defining methods
Java
1 void doSomething() {
2    // logic here
3 }
Kotlin
1 fun doSomething() {
2    // logic here
3 }
 

Variable number of arguments


Java
1 void doSomething(int... numbers) {
2    // logic here
3 }
Kotlin
1 fun doSomething(vararg numbers: Int) {
2    // logic here
3 }
 

Defining methods with return


Java
1 int getScore() {
2    // logic here
3    return score;
4 }
Kotlin
1 fun getScore(): Int {
2    // logic here
3    return score
4 }
5

6 // as a single-expression function
7

8 fun getScore(): Int = score


9

10 // even simpler (type will be determined automatically)


11

12 fun getScore() = score // return-type is Int


 

Returning result of an operation


Java
1 int getScore(int value) {
2     // logic here
3     return 2 * value;
4 }
Kotlin
1 fun getScore(value: Int): Int {
2    // logic here
3    return 2 * value
4 }
5

6 // as a single-expression function
7 fun getScore(value: Int): Int = 2 * value
8

9 // even simpler (type will be determined automatically)


10

11 fun getScore(value: Int) = 2 * value // return-type is int


 

Constructors
Java
1 public class Utils {
2

3     private Utils() {
4       // This utility class is not publicly instantiable
5     }
6

7     public static int getScore(int value) {


8         return 2 * value;
9     }
10

11 }
Kotlin
1 class Utils private constructor() {
2

3     companion object {
4

5         fun getScore(value: Int): Int {


6             return 2 * value
7         }
8

9     }
10 }
11

12 // another way
13

14 object Utils {
15

16     fun getScore(value: Int): Int {


17         return 2 * value
18     }
19

20 }
 

Getters and Setters


Java
1 public class Developer {
2

3     private String name;


4     private int age;
5

6     public Developer(String name, int age) {


7         this.name = name;
8         this.age = age;
9     }
10

11     public String getName() {


12         return name;
13     }
14

15     public void setName(String name) {


16         this.name = name;
17     }
18

19     public int getAge() {


20         return age;
21     }
22

23     public void setAge(int age) {


24         this.age = age;
25     }
26

27     @Override
28     public boolean equals(Object o) {
29         if (this == o) return true;
30         if (o == null || getClass() != o.getClass()) return fals
e;
31

32         Developer developer = (Developer) o;


33

34         if (age != developer.age) return false;


35         return name != null ? name.equals(developer.name) : deve
loper.name == null;
36

37     }
38

39     @Override
40     public int hashCode() {
41         int result = name != null ? name.hashCode() : 0;
42         result = 31 * result + age;
43         return result;
44     }
45

46     @Override
47     public String toString() {
48         return "Developer{" +
49                 "name='" + name + '\'' +
50                 ", age=" + age +
51                 '}';
52     }
53 }
Kotlin
data class Developer(var name: String, var age: Int)
 

Cloning or copying
Java
1 public class Developer implements Cloneable {
2

3     private String name;


4     private int age;
5

6     public Developer(String name, int age) {


7         this.name = name;
8         this.age = age;
9     }
10

11     @Override
12     protected Object clone() throws CloneNotSupportedException {
13         return (Developer)super.clone();
14     }
15 }
16

17 // cloning or copying
18 Developer dev = new Developer("Mindorks", 30);
19 try {
20     Developer dev2 = (Developer) dev.clone();
21 } catch (CloneNotSupportedException e) {
22     // handle exception
23 }
Kotlin
1 data class Developer(var name: String, var age: Int)
2

3 // cloning or copying
4 val dev = Developer("Mindorks", 30)
5 val dev2 = dev.copy()
6 // in case you only want to copy selected properties
7 val dev2 = dev.copy(age = 25)
 

Class methods
Java
1 public class Utils {
2

3     private Utils() {
4       // This utility class is not publicly instantiable
5     }
6

7     public static int triple(int value) {


8         return 3 * value;
9     }
10

11 }
12

13 int result = Utils.triple(3);


Kotlin
1 fun Int.triple(): Int {
2   return this * 3
3 }
4

5 var result = 3.triple()


 

Defining uninitialized objects


Java
Person person;
Kotlin
internal lateinit var person: Person
 

enum
Java
1 public enum Direction {
2         NORTH(1),
3         SOUTH(2),
4         WEST(3),
5         EAST(4);
6

7         int direction;
8

9         Direction(int direction) {
10             this.direction = direction;
11         }
12

13         public int getDirection() {


14             return direction;
15         }
16     }
Kotlin
1 enum class Direction constructor(direction: Int) {
2     NORTH(1),
3     SOUTH(2),
4     WEST(3),
5     EAST(4);
6

7     var direction: Int = 0


8         private set
9
10     init {
11         this.direction = direction
12     }
13 }
 

Sorting List
Java
1 List<Profile> profiles = loadProfiles(context);
2 Collections.sort(profiles, new Comparator<Profile>() {
3     @Override
4     public int compare(Profile profile1, Profile profile2) {
5         if (profile1.getAge() > profile2.getAge()) return 1;
6         if (profile1.getAge() < profile2.getAge()) return -1;
7         return 0;
8     }
9 });
Kotlin
1 val profile = loadProfiles(context)
2 profile.sortedWith(Comparator({ profile1, profile2 ->
3     if (profile1.age > profile2.age) return@Comparator 1
4     if (profile1.age < profile2.age) return@Comparator -1
5     return@Comparator 0
6 }))
 

Anonymous Class
Java
1  AsyncTask<Void, Void, Profile> task = new AsyncTask<Void, Void,
Profile>() {
2     @Override
3     protected Profile doInBackground(Void... voids) {
4         // fetch profile from API or DB
5         return null;
6     }
7

8     @Override
9     protected void onPreExecute() {
10         super.onPreExecute();
11         // do something
12     }
13 };
Kotlin
1 val task = object : AsyncTask<Void, Void, Profile>() {
2     override fun doInBackground(vararg voids: Void): Profile? {
3         // fetch profile from API or DB
4         return null
5     }
6

7     override fun onPreExecute() {


8         super.onPreExecute()
9         // do something
10     }
11 }

You might also like