当前位置: 首页 > 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…...

K8S认证|CKS题库+答案| 11. AppArmor

目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作&#xff1a; 1&#xff09;、切换集群 2&#xff09;、切换节点 3&#xff09;、切换到 apparmor 的目录 4&#xff09;、执行 apparmor 策略模块 5&#xff09;、修改 pod 文件 6&#xff09;、…...

PPT|230页| 制造集团企业供应链端到端的数字化解决方案:从需求到结算的全链路业务闭环构建

制造业采购供应链管理是企业运营的核心环节&#xff0c;供应链协同管理在供应链上下游企业之间建立紧密的合作关系&#xff0c;通过信息共享、资源整合、业务协同等方式&#xff0c;实现供应链的全面管理和优化&#xff0c;提高供应链的效率和透明度&#xff0c;降低供应链的成…...

零基础设计模式——行为型模式 - 责任链模式

第四部分&#xff1a;行为型模式 - 责任链模式 (Chain of Responsibility Pattern) 欢迎来到行为型模式的学习&#xff01;行为型模式关注对象之间的职责分配、算法封装和对象间的交互。我们将学习的第一个行为型模式是责任链模式。 核心思想&#xff1a;使多个对象都有机会处…...

让AI看见世界:MCP协议与服务器的工作原理

让AI看见世界&#xff1a;MCP协议与服务器的工作原理 MCP&#xff08;Model Context Protocol&#xff09;是一种创新的通信协议&#xff0c;旨在让大型语言模型能够安全、高效地与外部资源进行交互。在AI技术快速发展的今天&#xff0c;MCP正成为连接AI与现实世界的重要桥梁。…...

汇编常见指令

汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX&#xff08;不访问内存&#xff09;XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...

【从零开始学习JVM | 第四篇】类加载器和双亲委派机制(高频面试题)

前言&#xff1a; 双亲委派机制对于面试这块来说非常重要&#xff0c;在实际开发中也是经常遇见需要打破双亲委派的需求&#xff0c;今天我们一起来探索一下什么是双亲委派机制&#xff0c;在此之前我们先介绍一下类的加载器。 目录 ​编辑 前言&#xff1a; 类加载器 1. …...

WPF八大法则:告别模态窗口卡顿

⚙️ 核心问题&#xff1a;阻塞式模态窗口的缺陷 原始代码中ShowDialog()会阻塞UI线程&#xff0c;导致后续逻辑无法执行&#xff1a; var result modalWindow.ShowDialog(); // 线程阻塞 ProcessResult(result); // 必须等待窗口关闭根本问题&#xff1a…...

Xela矩阵三轴触觉传感器的工作原理解析与应用场景

Xela矩阵三轴触觉传感器通过先进技术模拟人类触觉感知&#xff0c;帮助设备实现精确的力测量与位移监测。其核心功能基于磁性三维力测量与空间位移测量&#xff0c;能够捕捉多维触觉信息。该传感器的设计不仅提升了触觉感知的精度&#xff0c;还为机器人、医疗设备和制造业的智…...

WEB3全栈开发——面试专业技能点P7前端与链上集成

一、Next.js技术栈 ✅ 概念介绍 Next.js 是一个基于 React 的 服务端渲染&#xff08;SSR&#xff09;与静态网站生成&#xff08;SSG&#xff09; 框架&#xff0c;由 Vercel 开发。它简化了构建生产级 React 应用的过程&#xff0c;并内置了很多特性&#xff1a; ✅ 文件系…...

热门Chrome扩展程序存在明文传输风险,用户隐私安全受威胁

赛门铁克威胁猎手团队最新报告披露&#xff0c;数款拥有数百万活跃用户的Chrome扩展程序正在通过未加密的HTTP连接静默泄露用户敏感数据&#xff0c;严重威胁用户隐私安全。 知名扩展程序存在明文传输风险 尽管宣称提供安全浏览、数据分析或便捷界面等功能&#xff0c;但SEMR…...