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 写法区别
原文链接: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版本为:Ubuntu 18.04 LTS。 当前版本安装的是:cuda10.1。 九天毕昇平台:https://jiutian.10086.cn/edu/#/home 一、linux下运行python的操作 ls 为列出当前目录中的文件 cd 文件名 进入…...
计算机组成原理 - 2. 数据的表示和运算
整理自天勤高分笔记,购书链接: 24 天勤高分笔记 要记住的几个数字 📓: 215327682^{15} 3276821532768 216655362^{16} 6553621665536 23121474836482^{31} 21474836482312147483648 23242949672962^{32} 4294967296232429496…...
【js】基础知识点--语句,break和continue,switch,with,for..in,do-while,while
一、break和continue语句,常用 break 语句会立即退出循环,强制继续执行循环后面的语句。而 continue 语句虽然也是立即退出循环,但退出循环后会从循环的顶部继续执行 var num 0; for (var i1; i < 10; i) {if (i % 5 0) {break;}num; …...
【C++】迭代器
内容来自《C Primer(第5版)》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 合并视频文件没声音,不同步原因
查了不少帖子也没搞明白,可能懂的人不会遇到吧。 1 没声音是因为我几个视频文件中,有的没音轨,就是用文字生成了个视频,需要先给它加个dummy的音轨才行。 2 视频不同步是因为各个视频格式不一样,参数挺多我也不知道具…...
绕不开的“定位”
绕开“定位”这个词谈企业战略和品牌 相当于揪住头发离开地球 定位这个词,已经进入商业界的心智中去了 发明这个词的特劳特和里斯的思想有啥差异? 《定位屋》刨析的很到位 趣讲大白话:把握概念的源头,就理解对了大部分 【趣讲信息…...
《Effective Objective-C 2.0 》 阅读笔记 item12
第12条:理解消息转发机制 1. 消息转发机制 当对象接收到无法解读的消息后,就会启动“消息转发”机制,开发者可经由此过程告诉对象应该如何处理未知消息。 消息转发分为两大阶段 第一阶段:先征询接收者所属的类,看其…...
云原生计算能消除技术债务吗?
云原生计算可以将行业领域驱动的设计、GitOps和其他现代软件最佳实践汇总起来,如果企业实施得当,可以减少技术债务。 云原生计算是企业IT的一种新范式,它涉及现代技术的方方面面,从应用程序开发到软件架构,再到保持一…...
9. 回文数
题目 给你一个整数 xxx ,如果 xxx 是一个回文整数,返回 truetruetrue ;否则,返回 falsefalsefalse 。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 例子 输入&am…...
[SV]SystemVerilog线程之fork...join专题
SystemVerilog线程之fork...join专题 Q:fork-join_none开辟的线程在外部任务退出后也会结束吗? A:后台线程不会结束,任何由fork开辟的线程(join、join_any、join_none),无论其外部任务ÿ…...
你看这个spring的aop它又大又宽
aop🚓AOP 分类AspectJ | 高级但是难用Spring AOP | 易用但仅支持方法aop 原理明月几时有,把酒问青天。——唐代李白《将进酒》 AOP 分类 在 Spring Boot 中,AOP 的实现主要有以下几种: 基于 AspectJ 的 AOP:这是一种基…...
设计模式-创建-单例模式
4.1.1 模式介绍 定义 单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一,此模式保证某个类在运行期间,只有一个实例对外提供服务,而这个类被称为单例类。 作用 保证一个类只有一个实例为该实例提供一个全…...
使用mybatis-plus-generator配置一套适合你的CRUD
1、maven引入 mybatis-plus-generator 和模板引擎,你也可以使用freemarker之类的,看个人 <!-- 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去表达一个数据,因为只能放0和1,能表达的数据太少了,内存地址最小单位是字节 11111111 0x0011 1字节8bit,8bit才算作一个地址,地址是以字节为最小单位&#…...
当你的IDE装上GPT
文章目录前言下载安装使用步骤前言 我们可能要从“CV”工程师变成“KL工程师了,为什么叫”KL“工程师呢, 因为只要K和L两个指令就可以直接生成代码、修改代码,哪行代码不会点哪里,他都给你解释得明明白白。 提示:以下…...
一图看懂 pathlib 模块:面向对象的文件系统路径, 资料整理+笔记(大全)
本文由 大侠(AhcaoZhu)原创,转载请声明。 链接: https://blog.csdn.net/Ahcao2008 一图看懂 pathlib 模块:面向对象的文件系统路径, 资料整理笔记(大全)摘要模块图类关系图模块全展开【pathlib】统计常量intbooltuple模块9 fnmatc…...
前端如何将node.js 和mongodb部署到linux服务器上
本文首发自掘金。 记录了我第一次成功部署node.js 和mongodb到linux服务器上了,期间也遇到一些小坑,但是网上各位大佬记录的文章帮了大忙,所以我也将过程记录了下来。 安装Node 使用nvm linux上安装node,肯定首选nvmÿ…...
web vue 项目 Docker化部署
Web 项目 Docker 化部署详细教程 目录 Web 项目 Docker 化部署概述Dockerfile 详解 构建阶段生产阶段 构建和运行 Docker 镜像 1. Web 项目 Docker 化部署概述 Docker 化部署的主要步骤分为以下几个阶段: 构建阶段(Build Stage):…...
【解密LSTM、GRU如何解决传统RNN梯度消失问题】
解密LSTM与GRU:如何让RNN变得更聪明? 在深度学习的世界里,循环神经网络(RNN)以其卓越的序列数据处理能力广泛应用于自然语言处理、时间序列预测等领域。然而,传统RNN存在的一个严重问题——梯度消失&#…...
三分算法与DeepSeek辅助证明是单峰函数
前置 单峰函数有唯一的最大值,最大值左侧的数值严格单调递增,最大值右侧的数值严格单调递减。 单谷函数有唯一的最小值,最小值左侧的数值严格单调递减,最小值右侧的数值严格单调递增。 三分的本质 三分和二分一样都是通过不断缩…...
MFE(微前端) Module Federation:Webpack.config.js文件中每个属性的含义解释
以Module Federation 插件详为例,Webpack.config.js它可能的配置和含义如下: 前言 Module Federation 的Webpack.config.js核心配置包括: name filename(定义应用标识) remotes(引用远程模块࿰…...
DeepSeek越强,Kimi越慌?
被DeepSeek吊打的Kimi,还有多少人在用? 去年,月之暗面创始人杨植麟别提有多风光了。90后清华学霸,国产大模型六小虎之一,手握十几亿美金的融资。旗下的AI助手Kimi烧钱如流水,单月光是投流就花费2个亿。 疯…...
echarts使用graphic强行给图增加一个边框(边框根据自己的图形大小设置)- 适用于无法使用dom的样式
pdf-lib https://blog.csdn.net/Shi_haoliu/article/details/148157624?spm1001.2014.3001.5501 为了完成在pdf中导出echarts图,如果边框加在dom上面,pdf-lib导出svg的时候并不会导出边框,所以只能在echarts图上面加边框 grid的边框是在图里…...
高抗扰度汽车光耦合器的特性
晶台光电推出的125℃光耦合器系列产品(包括KL357NU、KL3H7U和KL817U),专为高温环境下的汽车应用设计,具备以下核心优势和技术特点: 一、技术特性分析 高温稳定性 采用先进的LED技术和优化的IC设计,确保在…...
手动给中文分词和 直接用神经网络RNN做有什么区别
手动分词和基于神经网络(如 RNN)的自动分词在原理、实现方式和效果上有显著差异,以下是核心对比: 1. 实现原理对比 对比维度手动分词(规则 / 词典驱动)神经网络 RNN 分词(数据驱动)…...
基于 HTTP 的单向流式通信协议SSE详解
SSE(Server-Sent Events)详解 🧠 什么是 SSE? SSE(Server-Sent Events) 是 HTML5 标准中定义的一种通信机制,它允许服务器主动将事件推送给客户端(浏览器)。与传统的 H…...
今日行情明日机会——20250609
上证指数放量上涨,接近3400点,个股涨多跌少。 深证放量上涨,但有个小上影线,相对上证走势更弱。 2025年6月9日涨停股主要行业方向分析(基于最新图片数据) 1. 医药(11家涨停) 代表标…...
