Sure! I'll provide you with two examples: one for declaring a simple class with some properties and methods, and another for implementing a basic function that performs some arithmetic operations. Each example will have one variant in Java and one in Kotlin.
Example 1: Simple Class Definition
Java Version
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter and Setter for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter for age
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
// Method to display person's details
public void displayPersonDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person person = new Person("John Doe", 25);
person.displayPersonDetails();
}
}
Kotlin Version
class Person(private var name: String, private var age: Int) {
// Getter and Setter for name
var personName: String
get() = name
set(value) {
name = value
}
// Getter and Setter for age
var personAge: Int
get() = age
set(value) {
if (value > 0) {
age = value
}
}
// Method to display person's details
fun displayPersonDetails() {
println("Name: $name, Age: $age")
}
}
fun main() {
val person = Person("John Doe", 25)
person.displayPersonDetails()
}
Example 2: Basic Arithmetic Function
Java Version
public class ArithmeticOperations {
// Method to perform addition
public int add(int a, int b) {
return a + b;
}
// Method to perform subtraction
public int subtract(int a, int b) {
return a - b;
}
// Main method to demonstrate the arithmetic operations
public static void main(String[] args) {
ArithmeticOperations operations = new ArithmeticOperations();
int sum = operations.add(10, 5);
int difference = operations.subtract(10, 5);
System.out.println("Sum: " + sum); // Output: Sum: 15
System.out.println("Difference: " + difference); // Output: Difference: 5
}
}
Kotlin Version
class ArithmeticOperations {
// Function to perform addition
fun add(a: Int, b: Int): Int {
return a + b
}
// Function to perform subtraction
fun subtract(a: Int, b: Int): Int {
return a - b
}
}
fun main() {
val operations = ArithmeticOperations()
val sum = operations.add(10, 5)
val difference = operations.subtract(10, 5)
println("Sum: $sum") // Output: Sum: 15
println("Difference: $difference") // Output: Difference: 5
}
These examples illustrate the parallels and differences between Java and Kotlin in terms of syntax and language features. Kotlin's syntax is often more concise, utilizing features like default getters and setters, string interpolation, and less boilerplate code.