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ÿ…...
(十)学生端搭建
本次旨在将之前的已完成的部分功能进行拼装到学生端,同时完善学生端的构建。本次工作主要包括: 1.学生端整体界面布局 2.模拟考场与部分个人画像流程的串联 3.整体学生端逻辑 一、学生端 在主界面可以选择自己的用户角色 选择学生则进入学生登录界面…...
cf2117E
原题链接:https://codeforces.com/contest/2117/problem/E 题目背景: 给定两个数组a,b,可以执行多次以下操作:选择 i (1 < i < n - 1),并设置 或,也可以在执行上述操作前执行一次删除任意 和 。求…...
Java + Spring Boot + Mybatis 实现批量插入
在 Java 中使用 Spring Boot 和 MyBatis 实现批量插入可以通过以下步骤完成。这里提供两种常用方法:使用 MyBatis 的 <foreach> 标签和批处理模式(ExecutorType.BATCH)。 方法一:使用 XML 的 <foreach> 标签ÿ…...
如何应对敏捷转型中的团队阻力
应对敏捷转型中的团队阻力需要明确沟通敏捷转型目的、提升团队参与感、提供充分的培训与支持、逐步推进敏捷实践、建立清晰的奖励和反馈机制。其中,明确沟通敏捷转型目的尤为关键,团队成员只有清晰理解转型背后的原因和利益,才能降低对变化的…...
通过MicroSip配置自己的freeswitch服务器进行调试记录
之前用docker安装的freeswitch的,启动是正常的, 但用下面的Microsip连接不上 主要原因有可能一下几个 1、通过下面命令可以看 [rootlocalhost default]# docker exec -it freeswitch fs_cli -x "sofia status profile internal"Name …...
Python第七周作业
Python第七周作业 文章目录 Python第七周作业 1.使用open以只读模式打开文件data.txt,并逐行打印内容 2.使用pathlib模块获取当前脚本的绝对路径,并创建logs目录(若不存在) 3.递归遍历目录data,输出所有.csv文件的路径…...
华为OD机考- 简单的自动曝光/平均像素
import java.util.Arrays; import java.util.Scanner;public class DemoTest4 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint[] arr Array…...
[10-1]I2C通信协议 江协科技学习笔记(17个知识点)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17...
React 样式方案与状态方案初探
React 本身只提供了基础 UI 层开发范式,其他特性的支持需要借助相关社区方案实现。本文将介绍 React 应用体系中样式方案与状态方案的主流选择,帮助开发者根据项目需求做出合适的选择。 1. React 样式方案 1.1. 内联样式 (Inline Styles) 通过 style …...
spring中的@KafkaListener 注解详解
KafkaListener 是 Spring Kafka 提供的一个核心注解,用于标记一个方法作为 Kafka 消息的消费者。下面是对该注解的详细解析: 基本用法 KafkaListener(topics "myTopic", groupId "myGroup") public void listen(String message)…...
