تلخيص الإختلافات بين لغة كوتلن وجافا

جوجل قررت دعم لغة كوتلن لتكون اللغة الإفتراضية لمنصة أندرويد. جوجل حالياً تدعم لغة البرمجة كوتلن لتصبح قادر فى المستقبل على استخدامها لكل أنظمة التشغيل والمنصات للمواقع، لينكس، ويندوز، ماك أو إس، آى أو إس، وبالطبع الأندرويد. ولذلك أعتقد أنها ستكون مهمه وقوية مثل سى، و سى شارب، وجافا، وبايثون وبين لغات البرمجة الأكثر أهمية للمستقبل.

والآن وفى هذا الموضوع سنتعرض إلى طرق كتابة نفس الكود بلغة جافا، ولغة كوتلن ليصبح من السهل معرفة الفروق بين اللغتين ونقل خبراتك ومعارفك من لغة جافا إلى لغة كوتلن دون معاناه طويلة فى التعلم.

نبدأ بأكثر الأمور استخداماً وهى طباعة النصوص إلى الكونسول (printing to console):

Print to console (Java)

System.out.print("Abanoub Hanna");
System.out.println("Abanoub Hanna");

Print to console (Kotlin)

print("Abanoub Hanna")
println("Abanoub Hanna")

الثوابت والمتغيرات فى لغة جافا وكوتلن :

Constants and Variables (Java)

String name = "Abanoub Hanna";
final String name = "Abanoub Hanna";

Constants and Variables (Kotlin)

var name = "Abanoub Hanna"
val name = "Abanoub Hanna"

التعامل مع قيمة null فى كوتلن وجافا :

Assigning the null value (Java)

String otherName;
otherName = null;

Assigning the null value (Kotlin)

var otherName : String?
otherName = null

التأكد أن القيمة ليست null فى لغة كوتلن وجافا :

Verify if value is null (Java)

if (text != null) {
  int length = text.length();
}

Verify if value is null (Kotlin)

text?.let {
    val length = text.length
}
// or simply
val length = text?.length

دمج النصوص فى لغة جافا وكوتلن :

Concatenation of strings (Java)

String firstName = "Abanoub";
String lastName = "Hanna";
String message = "My name is: " + firstName + " " + lastName;

Concatenation of strings (Kotlin)

val firstName = "Abanoub"
val lastName = "Hanna"
val message = "My name is: $firstName $lastName"

اضافة سطر جديد فى لغة كوتلن وجافا :

New line in string (Java)

String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";

New line in string (Kotlin)

val text = """
        |First Line
        |Second Line
        |Third Line
        """.trimMargin()

الشرط القصير (ternary) فى لغة جافا وكوتلن :

Ternary Operations (Java)

String text = x > 5 ? "x > 5" : "x <= 5";

String message = null;
log(message != null ? message : "");

Ternary Operations (Kotlin)

val text = if (x > 5)
              "x > 5"
           else "x <= 5"

val message: String? = null
log(message ?: "")

العوامل المنطقية فى لغة جافا وكوتلن :

Logical Operators (Java)

final int andResult  = a & b;
final int orResult   = a | b;
final int xorResult  = a ^ b;
final int rightShift = a >> 2;
final int leftShift  = a << 2;
final int unsignedRightShift = a >>> 2;

Logical Operators (Kotlin)

val andResult  = a and b
val orResult   = a or b
val xorResult  = a xor b
val rightShift = a shr 2
val leftShift  = a shl 2
val unsignedRightShift = a ushr 2

معرفة النوع، والتحويل بين الأنواع فى لغة كوتلن وجافا :

Check the type and casting (Java)

if (object instanceof Car) {
}
Car car = (Car) object;

Check the type and casting (Kotlin)

if (object is Car) {
}
var car = object as Car

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

معرفة النوع والتحويل بالطريقة الضمنية فى لغة كوتلن وجافا :

Check the type and casting (implicit) (Java)

if (object instanceof Car) {
   Car car = (Car) object;
}

Check the type and casting (implicit) (Kotlin)

if (object is Car) {
   var car = object // smart casting
}

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

تعدد الشروط فى لغة جافا وكوتلن :

Multiple conditions (Java)

if (score >= 0 && score <= 300) { }

Multiple conditions (Kotlin)

if (score in 0..300) { }

تعدد إحتمالات الشرط والنتيجة فى لغة جافا وكوتلن :

Multiple Conditions (Switch case) (Java)

int score = // some score;
String grade;
switch (score) {
 case 10:
 case 9:
  grade = "Excellent";
  break;
 case 8:
 case 7:
 case 6:
  grade = "Good";
  break;
 case 5:
 case 4:
  grade = "OK";
  break;
 case 3:
 case 2:
 case 1:
  grade = "Fail";
  break;
 default:
     grade = "Fail";    
}

Multiple Conditions (ًwhen) (Kotlin)

var score = // some score
var grade = when (score) {
 9, 10 -> "Excellent"
 in 6..8 -> "Good"
 4, 5 -> "OK"
 in 1..3 -> "Fail"
 else -> "Fail"
}

التكرار فى لغة جافا وكوتلن :

For-loops (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 entry: map.entrySet()) { }

For-loops (Kotlin)

for (i in 1..10) { }

for (i in 1 until 10) { }

for (i in 10 downTo 0) { }

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

for (i in 10 downTo 1 step 2) { }

for (item in collection) { }

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

مجموعات البيانات فى لغة جافا وكوتلن :

Collections (Java)

final List listOfNumber = Arrays.asList(1, 2, 3, 4);

final Map keyValue = new HashMap();
map.put(1, "Abanoub");
map.put(2, "Kerellos");
map.put(3, "Hesham");

// Java 9
final List listOfNumber = List.of(1, 2, 3, 4);

final Map keyValue = Map.of(1, "Abanoub",
                                             2, "Kerellos",
                                             3, "Hesham");

Collections (Kotlin)

val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Abanoub",
                     2 to "Kerellos",
                     3 to "Hesham")

التكرار للحصول على كل العناصر فى لغة جافا وكوتلن :

for each (Java)

// Java 7 and below
for (Car car : cars) {
  System.out.println(car.speed);
}

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

// Java 7 and below
for (Car car : cars) {
  if (car.speed > 100) {
    System.out.println(car.speed);
  }
}

// Java 8+
cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

for each (Kotlin)

cars.forEach {
    println(it.speed)
}

cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}

// kotlin 1.1+
cars.stream().filter { it.speed > 100 }.forEach { println(it.speed)}
cars.parallelStream().filter { it.speed > 100 }.forEach { println(it.speed)}

شطر المصفوفات فى لغة جافا وكوتلن :

Splitting arrays (Java)

String[] splits = "param=car".split("=");
String param = splits[0];
String value = splits[1];

Splitting arrays (Kotlin)

val (param, value) = "param=car".split("=")

الـ Methods أو الـ Functions فى لغة جافا وكوتلن :

Defining methods (Java)

void doSomething() {
   // logic here
}

Defining methods (Kotlin)

fun doSomething() {
   // logic here
}

استخدام مدخلات (parameters or arguments) للدالة فى جافا وكوتلن :

Variable number of arguments (Java)

void doSomething(int... numbers) {
   // logic here
}

Variable number of arguments (Kotlin)

fun doSomething(vararg numbers: Int) {
   // logic here
}

تعريف دالة (ميثود) تعود لنا بشئ. فى جافا وكوتلن :

Defining methods with return (Java)

int getScore() {
   // logic here
   return score;
}

Defining methods with return (Kotlin)

fun getScore(): Int {
   // logic here
   return score
}

// as a single-expression function

fun getScore(): Int = score

// even simpler (type will be determined automatically)

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

إرجاع ناتج عملية فى كوتلن وجافا :

Returning result of an operation (Java)

int getScore(int value) {
    // logic here
    return 2 * value;
}

Returning result of an operation (Kotlin)

fun getScore(value: Int): Int {
   // logic here
   return 2 * value
}

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

// even simpler (type will be determined automatically)

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

الـ constructors فى لغة كوتلن وجافا :

Constructors (Java)

public class Utils {

    private Utils() {
      // This utility class is not publicly instantiable
    }

    public static int getScore(int value) {
        return 2 * value;
    }

}

Constructors (Kotlin)

class Utils private constructor() {

    companion object {

        fun getScore(value: Int): Int {
            return 2 * value
        }

    }
}

// another way

object Utils {

    fun getScore(value: Int): Int {
        return 2 * value
    }

}

كيف تكتب الـ setters و الـ getters فى لغة كوتلن ؟

Getters and Setters (Java)

public class Developer {

    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Developer developer = (Developer) o;

        if (age != developer.age) return false;
        return name != null ? name.equals(developer.name) : developer.name == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Developer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Getters and Setters (Kotlin)

data class Developer(var name: String, var age: Int)

الإستنساخ فى كوتلن وجافا :

Cloning or copying (Java)

public class Developer implements Cloneable {

    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return (Developer)super.clone();
    }
}

// cloning or copying
Developer dev = new Developer("Mindorks", 30);
try {
    Developer dev2 = (Developer) dev.clone();
} catch (CloneNotSupportedException e) {
    // handle exception
}

Cloning or copying (Kotlin)

data class Developer(var name: String, var age: Int)

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

استخدام الميثود من داخل الكلاس :

Class methods (Java)

public class Utils {

    private Utils() {
      // This utility class is not publicly instantiable
    }

    public static int triple(int value) {
        return 3 * value;
    }

}

int result = Utils.triple(3);

Class methods (Kotlin)

fun Int.triple(): Int {
  return this * 3
}

var result = 3.triple()

تعريف الأوبجكت بدون اعطاء قيمة :

Defining uninitialized objects (Java)

Person person;

Defining uninitialized objects (Kotlin)

internal lateinit var person: Person

كتابة مجموعة الإحتمالات المترابطة enum فى لغة كوتلن وجافا :

enum (Java)

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

        int direction;

        Direction(int direction) {
            this.direction = direction;
        }

        public int getDirection() {
            return direction;
        }
    }

enum (Kotlin)

enum class Direction constructor(direction: Int) {
    NORTH(1),
    SOUTH(2),
    WEST(3),
    EAST(4);

    var direction: Int = 0
        private set

    init {
        this.direction = direction
    }
}

ترتيب قائمة بلغة جافا وكوتلن :

Sorting List (Java)

List profiles = loadProfiles(context);
Collections.sort(profiles, new Comparator() {
    @Override
    public int compare(Profile profile1, Profile profile2) {
        if (profile1.getAge() > profile2.getAge()) return 1;
        if (profile1.getAge() < profile2.getAge()) return -1;
        return 0;
    }
});

Sorting List (Kotlin)

val profile = loadProfiles(context)
profile.sortedWith(Comparator({ profile1, profile2 ->
    if (profile1.age > profile2.age) return@Comparator 1
    if (profile1.age < profile2.age) return@Comparator -1
    return@Comparator 0
}))

الكلاس المجهول فى لغة كوتلن وجافا :

Anonymous Class (Java)

 AsyncTask task = new AsyncTask() {
    @Override
    protected Profile doInBackground(Void... voids) {
        // fetch profile from API or DB
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // do something
    }
};

Anonymous Class (Kotlin)

val task = object : AsyncTask() {
    override fun doInBackground(vararg voids: Void): Profile? {
        // fetch profile from API or DB
        return null
    }

    override fun onPreExecute() {
        super.onPreExecute()
        // do something
    }
}
أتمنى أن تكونوا استفدتم من هذه الأمثلة المتساويه باللغتين. سيتم شرح كلا اللغتين بشكل أكثر وضوحاً قريباً على الموقع هنا إن شاء الله.

0 comments:

إرسال تعليق