当前位置: 首页 > news >正文

java与kotlin 写法区别

原文链接:https://gitcode.net/mirrors/mindorksopensource/from-java-to-kotlin?utm_source=csdn_github_accelerator#assigning-the-null-value

Print to Console 打印到控制台

Java

System.out.print("Amit Shekhar");
System.out.println("Amit Shekhar");

Kotlin

print("Amit Shekhar")
println("Amit Shekhar")

Constants and Variables 常量和变量

Java

String name = "Amit Shekhar";
final String name = "Amit Shekhar";

Kotlin

var name = "Amit Shekhar"
val name = "Amit Shekhar"

Assigning the null value 分配空值

Java

String otherName;
otherName = null;

Kotlin

var otherName : String?
otherName = null

Verify if value is null 验证值是否为空

Java

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

Kotlin

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

Verify if value is NotNull OR NotEmpty 验证值是否为 NotNull 或 NotEmpty

Java

String sampleString = "Shekhar";
if (!sampleString.isEmpty()) {myTextView.setText(sampleString);
}
if(sampleString!=null && !sampleString.isEmpty()){myTextView.setText(sampleString); 
}

Kotlin

var sampleString ="Shekhar"
if(sampleString.isNotEmpty()){  //the feature of kotlin extension functionmyTextView.text=sampleString
}
if(!sampleString.isNullOrEmpty()){myTextView.text=sampleString 
}

Concatenation of strings 字符串的连接

Java

String firstName = "Amit";
String lastName = "Shekhar";
String message = "My name is: " + firstName + " " + lastName;

Kotlin

var firstName = "Amit"
var lastName = "Shekhar"
var message = "My name is: $firstName $lastName"

New line in string 字符串中的新行

Java

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

Kotlin

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

Substring

Java

String str = "Java to Kotlin Guide";
String substr = "";//print java
substr = str.substring(0, 4);
System.out.println("substring = " + substr);//print kotlin
substr = str.substring(8, 14);
System.out.println("substring = " + substr);

Kotlin

var str = "Java to Kotlin Guide"
var substr = ""//print java
substr = str.substring(0..3) //
println("substring $substr")//print kotlin
substr = str.substring(8..13)
println("substring $substr")

Ternary Operations 三元运算

Java

String text = x > 5 ? "x > 5" : "x <= 5";String message = null;
log(message != null ? message : "");

Kotlin

val text = if (x > 5) "x > 5" else "x <= 5"val message: String? = null
log(message ?: "")

Bitwise 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;

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;
}

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;
}

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) { }

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";				
}

Kotlin

var score = // some score
var grade = when (score) {9, 10 -> "Excellent"in 6..8 -> "Good"4, 5 -> "OK"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<String, String> entry: map.entrySet()) { }

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 0 step 2) { }for (item in collection) { }for ((key, value) in map) { }

Collections

Java

final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);final Map<Integer, String> keyValue = new HashMap<Integer, String>();
map.put(1, "Amit");
map.put(2, "Anand");
map.put(3, "Messi");// Java 9
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);final Map<Integer, String> keyValue = Map.of(1, "Amit",2, "Anand",3, "Messi");

Kotlin

val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Amit",2 to "Anand",3 to "Messi")

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));
cars.parallelStream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

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];

kotlin

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

Defining methods

Java

void doSomething() {// logic here
}

Kotlin

fun doSomething() {// logic here
}

Default values for method parameters 方法参数的默认值

Java

double calculateCost(int quantity, double pricePerItem) {return pricePerItem * quantity;
}double calculateCost(int quantity) {// default price is 20.5return 20.5 * quantity;
}

Kotlin

fun calculateCost(quantity: Int, pricePerItem: Double = 20.5) = quantity * pricePerItemcalculateCost(10, 25.0) // 250
calculateCost(10) // 205

Variable number of arguments 可变数量的参数

Java

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

Kotlin

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

Defining methods with return 用 return 定义方法

Java

int getScore() {// logic herereturn score;
}

Kotlin

fun getScore(): Int {// logic herereturn score
}// as a single-expression functionfun 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 herereturn 2 * value;
}

Kotlin

fun getScore(value: Int): Int {// logic herereturn 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

Java

public class Utils {private Utils() {// This utility class is not publicly instantiable}public static int getScore(int value) {return 2 * value;}}

Kotlin

class Utils private constructor() {companion object {fun getScore(value: Int): Int {return 2 * value}}
}// another wayobject Utils {fun getScore(value: Int): Int {return 2 * value}}

Getters and Setters getter 和 setter

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;}@Overridepublic 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;}@Overridepublic int hashCode() {int result = name != null ? name.hashCode() : 0;result = 31 * result + age;return result;}@Overridepublic String toString() {return "Developer{" +"name='" + name + '\'' +", age=" + age +'}';}
}

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;}@Overrideprotected Object clone() throws CloneNotSupportedException {return (Developer)super.clone();}
}// cloning or copying
Developer dev = new Developer("Messi", 30);
try {Developer dev2 = (Developer) dev.clone();
} catch (CloneNotSupportedException e) {// handle exception
}

Kotlin

data class Developer(var name: String, var age: Int)// cloning or copying
val dev = Developer("Messi", 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);

Generics

Java

// Example #1
interface SomeInterface<T> {void doSomething(T data);
}class SomeClass implements SomeInterface<String> {@Overridepublic void doSomething(String data) {// some logic}
}// Example #2
interface SomeInterface<T extends Collection<?>> {void doSomething(T data);
}class SomeClass implements SomeInterface<List<String>> {@Overridepublic void doSomething(List<String> data) {// some logic}
}
interface SomeInterface<T> {fun doSomething(data: T)
}class SomeClass: SomeInterface<String> {override fun doSomething(data: String) {// some logic}
}interface SomeInterface<T: Collection<*>> {fun doSomething(data: T)
}class SomeClass: SomeInterface<List<String>> {override fun doSomething(data: List<String>) {// some logic}
}

Kotlin

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

Defining uninitialized objects 定义未初始化的对象

Java

Person person;

Kotlin

internal lateinit var person: Person

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;}}

Kotlin

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

Sorting List

Java

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

Kotlin

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

Anonymous Class

Java

 AsyncTask<Void, Void, Profile> task = new AsyncTask<Void, Void, Profile>() {@Overrideprotected Profile doInBackground(Void... voids) {// fetch profile from API or DBreturn null;}@Overrideprotected void onPreExecute() {super.onPreExecute();// do something}
};

Kotlin

val task = object : AsyncTask<Void, Void, Profile>() {override fun doInBackground(vararg voids: Void): Profile? {// fetch profile from API or DBreturn null}override fun onPreExecute() {super.onPreExecute()// do something}
}

Initialization block 初始化块

Java

public class User {{  //Initialization blockSystem.out.println("Init block");}
}

Kotlin

   class User {init { // Initialization blockprintln("Init block")}}

相关文章:

java与kotlin 写法区别

原文链接&#xff1a;https://gitcode.net/mirrors/mindorksopensource/from-java-to-kotlin?utm_sourcecsdn_github_accelerator#assigning-the-null-value Print to Console 打印到控制台 Java System.out.print("Amit Shekhar"); System.out.println("Amit…...

服务器运行深度学习代码使用指南

该内容配置均在九天毕昇下配置。 当前系统使用的linux版本为&#xff1a;Ubuntu 18.04 LTS。 当前版本安装的是&#xff1a;cuda10.1。 九天毕昇平台&#xff1a;https://jiutian.10086.cn/edu/#/home 一、linux下运行python的操作 ls 为列出当前目录中的文件 cd 文件名 进入…...

计算机组成原理 - 2. 数据的表示和运算

整理自天勤高分笔记&#xff0c;购书链接&#xff1a; 24 天勤高分笔记 要记住的几个数字 &#x1f4d3;&#xff1a; 215327682^{15} 3276821532768 216655362^{16} 6553621665536 23121474836482^{31} 21474836482312147483648 23242949672962^{32} 4294967296232429496…...

【js】基础知识点--语句,break和continue,switch,with,for..in,do-while,while

一、break和continue语句&#xff0c;常用 break 语句会立即退出循环&#xff0c;强制继续执行循环后面的语句。而 continue 语句虽然也是立即退出循环&#xff0c;但退出循环后会从循环的顶部继续执行 var num 0; for (var i1; i < 10; i) {if (i % 5 0) {break;}num; …...

【C++】迭代器

内容来自《C Primer&#xff08;第5版&#xff09;》9.2.1 迭代器、9.2.3 begin和end成员、9.3.6 容器操作可能使迭代器失效、10.4.3 反向迭代器 目录 1. 迭代器 1.1 迭代器范围 1.2 使用左闭合范围蕴含的编程假定 2. begin和end成员 3. 容器操作可能使迭代器失效 3.1 编…...

数据可视化在前端中的应用

前端开发中,数据可视化是一种非常重要的技术。它可以将复杂的数据以图形化的方式展示出来,让用户更容易理解和分析数据。在前端中,VUE是一种非常流行的JavaScript框架,可以用来实现各种数据可视化效果。 首先,让我们来看看一些常见的数据可视化方式: 表格:表格是数据可…...

FFmpeg 合并视频文件没声音,不同步原因

查了不少帖子也没搞明白&#xff0c;可能懂的人不会遇到吧。 1 没声音是因为我几个视频文件中&#xff0c;有的没音轨&#xff0c;就是用文字生成了个视频&#xff0c;需要先给它加个dummy的音轨才行。 2 视频不同步是因为各个视频格式不一样&#xff0c;参数挺多我也不知道具…...

绕不开的“定位”

绕开“定位”这个词谈企业战略和品牌 相当于揪住头发离开地球 定位这个词&#xff0c;已经进入商业界的心智中去了 发明这个词的特劳特和里斯的思想有啥差异&#xff1f; 《定位屋》刨析的很到位 趣讲大白话&#xff1a;把握概念的源头&#xff0c;就理解对了大部分 【趣讲信息…...

《Effective Objective-C 2.0 》 阅读笔记 item12

第12条&#xff1a;理解消息转发机制 1. 消息转发机制 当对象接收到无法解读的消息后&#xff0c;就会启动“消息转发”机制&#xff0c;开发者可经由此过程告诉对象应该如何处理未知消息。 消息转发分为两大阶段 第一阶段&#xff1a;先征询接收者所属的类&#xff0c;看其…...

云原生计算能消除技术债务吗?

云原生计算可以将行业领域驱动的设计、GitOps和其他现代软件最佳实践汇总起来&#xff0c;如果企业实施得当&#xff0c;可以减少技术债务。 云原生计算是企业IT的一种新范式&#xff0c;它涉及现代技术的方方面面&#xff0c;从应用程序开发到软件架构&#xff0c;再到保持一…...

9. 回文数

题目 给你一个整数 xxx &#xff0c;如果 xxx 是一个回文整数&#xff0c;返回 truetruetrue &#xff1b;否则&#xff0c;返回 falsefalsefalse 。回文数是指正序&#xff08;从左向右&#xff09;和倒序&#xff08;从右向左&#xff09;读都是一样的整数。 例子 输入&am…...

[SV]SystemVerilog线程之fork...join专题

SystemVerilog线程之fork...join专题 Q&#xff1a;fork-join_none开辟的线程在外部任务退出后也会结束吗&#xff1f; A&#xff1a;后台线程不会结束&#xff0c;任何由fork开辟的线程&#xff08;join、join_any、join_none&#xff09;&#xff0c;无论其外部任务&#xff…...

你看这个spring的aop它又大又宽

aop&#x1f693;AOP 分类AspectJ | 高级但是难用Spring AOP | 易用但仅支持方法aop 原理明月几时有&#xff0c;把酒问青天。——唐代李白《将进酒》 AOP 分类 在 Spring Boot 中&#xff0c;AOP 的实现主要有以下几种&#xff1a; 基于 AspectJ 的 AOP&#xff1a;这是一种基…...

设计模式-创建-单例模式

4.1.1 模式介绍 定义 单例模式&#xff08;Singleton Pattern&#xff09;是 Java 中最简单的设计模式之一&#xff0c;此模式保证某个类在运行期间&#xff0c;只有一个实例对外提供服务&#xff0c;而这个类被称为单例类。 作用 保证一个类只有一个实例为该实例提供一个全…...

使用mybatis-plus-generator配置一套适合你的CRUD

1、maven引入 mybatis-plus-generator 和模板引擎&#xff0c;你也可以使用freemarker之类的&#xff0c;看个人 <!-- mybatisplus代码生成器 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactI…...

MATLAB实现各种离散概率密度函数(概率密度/分布/逆概率分布函数)

MATLAB实现各种离散概率密度函数(概率密度/分布/逆概率分布函数) 1 常见离散概率分布的基本信息2 常见离散概率分布计算及MATLAB实现2.1 二项分布(Binomial Distribution)2.1.1 常用函数2.2 负二项分布(Negative Binomial Distribution)2.2.1 常用函数2.3 几何分布(Geom…...

指针的基本知识

我们不会用bit去表达一个数据&#xff0c;因为只能放0和1&#xff0c;能表达的数据太少了&#xff0c;内存地址最小单位是字节 11111111 0x0011 1字节8bit,8bit才算作一个地址&#xff0c;地址是以字节为最小单位&#…...

当你的IDE装上GPT

文章目录前言下载安装使用步骤前言 我们可能要从“CV”工程师变成“KL工程师了&#xff0c;为什么叫”KL“工程师呢&#xff0c; 因为只要K和L两个指令就可以直接生成代码、修改代码&#xff0c;哪行代码不会点哪里&#xff0c;他都给你解释得明明白白。 提示&#xff1a;以下…...

一图看懂 pathlib 模块:面向对象的文件系统路径, 资料整理+笔记(大全)

本文由 大侠(AhcaoZhu)原创&#xff0c;转载请声明。 链接: https://blog.csdn.net/Ahcao2008 一图看懂 pathlib 模块&#xff1a;面向对象的文件系统路径, 资料整理笔记&#xff08;大全&#xff09;摘要模块图类关系图模块全展开【pathlib】统计常量intbooltuple模块9 fnmatc…...

前端如何将node.js 和mongodb部署到linux服务器上

本文首发自掘金。 记录了我第一次成功部署node.js 和mongodb到linux服务器上了&#xff0c;期间也遇到一些小坑&#xff0c;但是网上各位大佬记录的文章帮了大忙&#xff0c;所以我也将过程记录了下来。 安装Node 使用nvm linux上安装node&#xff0c;肯定首选nvm&#xff…...

业务系统对接大模型的基础方案:架构设计与关键步骤

业务系统对接大模型&#xff1a;架构设计与关键步骤 在当今数字化转型的浪潮中&#xff0c;大语言模型&#xff08;LLM&#xff09;已成为企业提升业务效率和创新能力的关键技术之一。将大模型集成到业务系统中&#xff0c;不仅可以优化用户体验&#xff0c;还能为业务决策提供…...

日语AI面试高效通关秘籍:专业解读与青柚面试智能助攻

在如今就业市场竞争日益激烈的背景下&#xff0c;越来越多的求职者将目光投向了日本及中日双语岗位。但是&#xff0c;一场日语面试往往让许多人感到步履维艰。你是否也曾因为面试官抛出的“刁钻问题”而心生畏惧&#xff1f;面对生疏的日语交流环境&#xff0c;即便提前恶补了…...

Vue记事本应用实现教程

文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展&#xff1a;显示创建时间8. 功能扩展&#xff1a;记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

蓝牙 BLE 扫描面试题大全(2):进阶面试题与实战演练

前文覆盖了 BLE 扫描的基础概念与经典问题蓝牙 BLE 扫描面试题大全(1)&#xff1a;从基础到实战的深度解析-CSDN博客&#xff0c;但实际面试中&#xff0c;企业更关注候选人对复杂场景的应对能力&#xff08;如多设备并发扫描、低功耗与高发现率的平衡&#xff09;和前沿技术的…...

【ROS】Nav2源码之nav2_behavior_tree-行为树节点列表

1、行为树节点分类 在 Nav2(Navigation2)的行为树框架中,行为树节点插件按照功能分为 Action(动作节点)、Condition(条件节点)、Control(控制节点) 和 Decorator(装饰节点) 四类。 1.1 动作节点 Action 执行具体的机器人操作或任务,直接与硬件、传感器或外部系统…...

【Go】3、Go语言进阶与依赖管理

前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课&#xff0c;做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程&#xff0c;它的核心机制是 Goroutine 协程、Channel 通道&#xff0c;并基于CSP&#xff08;Communicating Sequential Processes&#xff0…...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

【学习笔记】深入理解Java虚拟机学习笔记——第4章 虚拟机性能监控,故障处理工具

第2章 虚拟机性能监控&#xff0c;故障处理工具 4.1 概述 略 4.2 基础故障处理工具 4.2.1 jps:虚拟机进程状况工具 命令&#xff1a;jps [options] [hostid] 功能&#xff1a;本地虚拟机进程显示进程ID&#xff08;与ps相同&#xff09;&#xff0c;可同时显示主类&#x…...

Golang——6、指针和结构体

指针和结构体 1、指针1.1、指针地址和指针类型1.2、指针取值1.3、new和make 2、结构体2.1、type关键字的使用2.2、结构体的定义和初始化2.3、结构体方法和接收者2.4、给任意类型添加方法2.5、结构体的匿名字段2.6、嵌套结构体2.7、嵌套匿名结构体2.8、结构体的继承 3、结构体与…...

【 java 虚拟机知识 第一篇 】

目录 1.内存模型 1.1.JVM内存模型的介绍 1.2.堆和栈的区别 1.3.栈的存储细节 1.4.堆的部分 1.5.程序计数器的作用 1.6.方法区的内容 1.7.字符串池 1.8.引用类型 1.9.内存泄漏与内存溢出 1.10.会出现内存溢出的结构 1.内存模型 1.1.JVM内存模型的介绍 内存模型主要分…...