大家好,我是光子郎,现如今,在Android开发中,Kotlin相信一直是大家的学习方向,那么今天,我将带大家看一看同样的JAVA代码用Kotlin应该怎么写吧,废话少说,开整!

目录

1.变量声明和初始化

2.可空类型

3.函数定义

4.字符串插值

5.条件语句

6.循环语句

7.列表初始化

8.列表遍历

9.扩展函数

10.空安全调用

11.对象实例化

12.静态方法调用

13.默认参数值

14.可变参数

15.数据类

16.扩展属性

17.Lambda表达式

18.过滤列表

19.使用扩展函数过滤列表

20.使用Stream操作过滤列表

21.使用map操作变换列表元素

22.使用Map集合

23.使用函数引用

24.使用委托类实现接口

25.使用Lambda表达式实现接口

26.使用lateinit修饰符

27.使用协程进行异步操作

28.使用对象表达式创建匿名类

29.使用委托属性

30.使用companion object创建静态成员

31.使用安全调用操作符

32.使用 Elvis 操作符

33.使用区间

34.使用区间并指定步长

35.使用区间反向迭代

36.使用条件表达式

37.使用类型推断

38.使用标签和跳转

39.使用标准库函数

40.使用顶层函数

41.使用单例对象

42.使用函数类型和高阶函数

43.使用委托类实现属性

44.使用扩展函数操作集合

45.使用Lambda表达式过滤集合

46.使用集合函数操作集合

47.使用with函数简化代码块

48.使用apply函数初始化对象

49.使用run函数执行可为空的代码块

50.使用use函数自动关闭资源


1.变量声明和初始化

JAVA:

String name = "John";
int age = 25;

kotlin:

val name: String = "John"
val age: Int = 25

2.可空类型

JAVA:

String nullableName = null;

Kotlin:

val nullableName: String? = null

3.函数定义

JAVA:

public void greet(String name) {
    System.out.println("Hello, " + name + "!");
}

Kotlin:

fun greet(name: String) {
    println("Hello, $name!")
}

4.字符串插值

JAVA:

String name = "John";
System.out.println("My name is " + name);

Kotlin:

val name = "John"
println("My name is $name")

5.条件语句

JAVA:

int number = 5;
if (number > 0) {
    System.out.println("Positive");
} else if (number < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Kotlin:

val number = 5
when {
    number > 0 -> println("Positive")
    number < 0 -> println("Negative")
    else -> println("Zero")
}

6.循环语句

JAVA:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Kotlin:

for (i in 0 until 5) {
    println(i)
}

7.列表初始化

JAVA:

List<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");

Kotlin:

val names = listOf("John", "Alice")

8.列表遍历

JAVA:

List<String> names = Arrays.asList("John", "Alice");
for (String name : names) {
    System.out.println(name);
}

Kotlin:

val names = listOf("John", "Alice")
for (name in names) {
    println(name)
}

9.扩展函数

JAVA:

public static String capitalize(String input) {
    return input.substring(0, 1).toUpperCase() + input.substring(1);
}

Kotlin:

fun String.capitalize(): String {
    return this.substring(0, 1).toUpperCase() + this.substring(1)
}

10.空安全调用

JAVA:

String nullableName = null;
int length = nullableName != null ? nullableName.length() : 0;

Kotlin:

val nullableName: String? = null
val length = nullableName?.length ?: 0

11.对象实例化

JAVA:

MyClass myClass = new MyClass();

Kotlin:

val myClass = MyClass()

12.静态方法调用

JAVA:

int result = Math.max(5, 10);

Kotlin:

val result = max(5, 10)

13.默认参数值

JAVA:

public void greet(String name, String message) {
    System.out.println("Hello, " + name + "! " + message);
}

public void greet(String name) {
    greet(name, "Welcome!");
}

Kotlin:

fun greet(name: String, message: String = "Welcome!") {
    println("Hello, $name! $message")
}

14.可变参数

JAVA:

public void printNumbers(int... numbers) {
    for (int number : numbers) {
        System.out.println(number);
    }
}

Kotlin:

fun printNumbers(vararg numbers: Int) {
    for (number in numbers) {
        println(number)
    }
}

15.数据类

JAVA:

public class Person {
    private String name;
    private int age;

    // Constructors, getters, setters, toString
}

Kotlin:

data class Person(val name: String, val age: Int)

16.扩展属性

Kotlin:

val String.firstChar: Char
    get() = this[0]

17.Lambda表达式

JAVA:

Runnable runnable = () -> System.out.println("Hello");

Kotlin:

val runnable: Runnable = { println("Hello") }

18.过滤列表

JAVA:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = new ArrayList<>();
for (Integer number : numbers) {
    if (number % 2 == 0) {
        evenNumbers.add(number);
    }
}

Kotlin:

val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }

19.使用扩展函数过滤列表

JAVA:

List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> filteredNames = new ArrayList<>();
for (String name : names) {
    if (name.length() > 4) {
        filteredNames.add(name);
    }
}

Kotlin:

val names = listOf("John", "Alice", "Bob")
val filteredNames = names.filter { it.length > 4 }

20.使用Stream操作过滤列表

JAVA:

List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> filteredNames = names.stream()
        .filter(name -> name.length() > 4)
        .collect(Collectors.toList());

Kotlin:

val names = listOf("John", "Alice", "Bob")
val filteredNames = names.filter { it.length > 4 }

21.使用map操作变换列表元素

JAVA:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squaredNumbers = new ArrayList<>();
for (Integer number : numbers) {
    squaredNumbers.add(number * number);
}

Kotlin:

val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }

22.使用Map集合

JAVA:

Map<String, Integer> ages = new HashMap<>();
ages.put("John", 25);
ages.put("

Kotlin:

val ages = mapOf("John" to 25, "Alice" to 30)

23.使用函数引用

JAVA:

List<String> names = Arrays.asList("John", "Alice", "Bob");
names.forEach(System.out::println);

Kotlin:

val names = listOf("John", "Alice", "Bob")
names.forEach(::println)

24.使用委托类实现接口

JAVA:

public class MyListener implements OnClickListener {
    @Override
    public void onClick(View view) {
        // Handle click event
    }
}

Kotlin:

class MyListener : OnClickListener {
    override fun onClick(view: View) {
        // Handle click event
    }
}

25.使用Lambda表达式实现接口

JAVA:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Handle click event
    }
});

Kotlin:

button.setOnClickListener { view ->
    // Handle click event
}

26.使用lateinit修饰符

Kotlin:

lateinit var name: String

27.使用协程进行异步操作

Kotlin:

viewModelScope.launch {
    val result = async { fetchData() }
    val data = result.await()
    // Process data
}

28.使用对象表达式创建匿名类

JAVA:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Run code
    }
};

Kotlin:

val runnable = object : Runnable {
    override fun run() {
        // Run code
    }
}

29.使用委托属性

Kotlin:

val lazyValue: String by lazy {
    // Compute the value
    "Hello"
}

30.使用companion object创建静态成员

JAVA:

public class MyClass {
    public static final String NAME = "John";
}

Kotlin:

class MyClass {
    companion object {
        const val NAME = "John"
    }
}

31.使用安全调用操作符

JAVA:

String nullableName = null;
int length = nullableName != null ? nullableName.length() : 0;

Kotlin:

val nullableName: String? = null
val length = nullableName?.length ?: 0

32.使用 Elvis 操作符

JAVA:

String nullableName = null;
String nonNullableName = nullableName != null ? nullableName : "Unknown";

Kotlin:

val nullableName: String? = null
val nonNullableName = nullableName ?: "Unknown"

33.使用区间

JAVA:

for (int i = 0; i <= 10; i++) {
    System.out.println(i);
}

Kotlin:

for (i in 0..10) {
    println(i)
}

34.使用区间并指定步长

JAVA:

for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);
}

Kotlin:

for (i in 0..10 step 2) {
    println(i)
}

35.使用区间反向迭代

JAVA:

for (int i = 10; i >= 0; i--) {
    System.out.println(i);
}

Kotlin:

for (i in 10 downTo 0) {
    println(i)
}

36.使用条件表达式

JAVA:

int a = 5;
int b = 10;
int max = a > b ? a : b;

Kotlin:

val a = 5
val b = 10
val max = if (a > b) a else b

37.使用类型推断

JAVA:

List<String> names = new ArrayList<>();

Kotlin:

val names = mutableListOf<String>()

38.使用标签和跳转

JAVA:

outerLoop: for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        if (j == 3) {
            break outerLoop;
        }
        System.out.println("i: " + i + ", j: " + j);
    }
}

Kotlin:

outerLoop@ for (i in 0 until 5) {
    for (j in 0 until 5) {
        if (j == 3) {
            break@outerLoop
        }
        println("i: $i, j: $j")
    }
}

39.使用标准库函数

JAVA:

List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> upperCaseNames = new ArrayList<>();
for (String name : names) {
    upperCaseNames.add(name.toUpperCase());
}

Kotlin:

val names = listOf("John", "Alice", "Bob")
val upperCaseNames = names.map { it.toUpperCase() }

40.使用顶层函数

JAVA:

public class Utils {
    public static int add(int a, int b) {
        return a + b;
    }
}

Kotlin:

fun add(a: Int, b: Int): Int {
    return a + b
}

41.使用单例对象

JAVA:

public class MySingleton {
    private static MySingleton instance;

    private MySingleton() {
        // Private constructor
    }

    public static MySingleton getInstance() {
        if (instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }
}

Kotlin:

object MySingleton {
    // Single instance
}

42.使用函数类型和高阶函数

JAVA:

public interface MyListener {
    void onClick(View view);
}

public class Button {
    private MyListener listener;

    public void setOnClickListener(MyListener listener) {
        this.listener = listener;
    }

    public void click() {
        if (listener != null) {
            listener.onClick(this);
        }
    }
}

Kotlin:

typealias MyListener = (view: View) -> Unit

class Button {
    private var listener: MyListener? = null

    fun setOnClickListener(listener: MyListener) {
        this.listener = listener
    }

    fun click() {
        listener?.invoke(this)
    }
}

43.使用委托类实现属性

JAVA:

public class MyDelegate {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

public class MyClass {
    private MyDelegate delegate = new MyDelegate();

    public String getValue() {
        return delegate.getValue();
    }

    public void setValue(String value) {
        delegate.setValue(value);
    }
}

Kotlin:

class MyDelegate {
    var value: String by Delegates.observable("") { _, old, new ->
        // Handle value changes
    }
}

class MyClass {
    private val delegate = MyDelegate()

    var value: String
        get() = delegate.value
        set(value) {
            delegate.value = value
        }
}

44.使用扩展函数操作集合

JAVA:

List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> uppercaseNames = new ArrayList<>();
for (String name : names) {
    uppercaseNames.add(name.toUpperCase());
}

Kotlin:

val names = listOf("John", "Alice", "Bob")
val uppercaseNames = names.map { it.toUpperCase() }

45.使用Lambda表达式过滤集合

JAVA:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = new ArrayList<>();
for (Integer number : numbers) {
    if (number % 2 == 0) {
        evenNumbers.add(number);
    }
}

Kotlin:

val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }

46.使用集合函数操作集合

JAVA:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = 0;
for (Integer number : numbers) {
    sum += number;
}

Kotlin:

val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.sum()

47.使用with函数简化代码块

JAVA:

StringBuilder builder = new StringBuilder();
builder.append("Hello");
builder.append(" ");
builder.append("World");
String result = builder.toString();

Kotlin:

val result = with(StringBuilder()) {
    append("Hello")
    append(" ")
    append("World")
    toString()
}

48.使用apply函数初始化对象

JAVA:

Person person = new Person();
person.setName("John");
person.setAge(25);

Kotlin:

val person = Person().apply {
    name = "John"
    age = 25
}

49.使用run函数执行可为空的代码块

JAVA:

String nullableName = null;
int length = 0;
if (nullableName != null) {
    length = nullableName.length();
}

Kotlin:

val nullableName: String? = null
val length = nullableName?.run { length } ?: 0

50.使用use函数自动关闭资源

JAVA:

InputStream inputStream = new FileInputStream("file.txt");
try {
    // Read from the input stream
} finally {
    if (inputStream != null) {
        inputStream.close();
    }
}

Kotlin:

val inputStream = FileInputStream("file.txt")
inputStream.use {
    // Read from the input stream
}

以上就是Android开发中JAVA代码写法与kotlin的区别,希望能够帮助大家在开发过程中提高kotlin开发的效率~

🍓🍓🍓🍓🍓这次的分享就到这里,不要忘记关注光子郎,也点点文末小卡片,一定会有你喜欢的资源分享以及干货整理,我们下期再见啦,拜拜~

05-29 10:14