Java 与 Kotlin 的语法对照
来源:互联网 发布:怎么联系淘宝达人合作 编辑:程序博客网 时间:2024/06/06 00:52
原文链接:http://www.jcodecraeer.com/demo/from-java-to-kotlin/index.html
一:Basic
Print
Java
System.out.print("Hello, World!");System.out.println("Hello, World!");
Kotlin
print("Hello, World!")println("Hello, World!")
Variables I
Java
final int x;final int y = 1;
Kotlin
val x: Intval y = 1
Variables II
Java
int w;int z = 2;z = 3;w = 1;
Kotlin
var w: Intvar z = 2z = 3w = 1
Null I
Java
final String name = null;String lastName;lastName = null
Kotlin
val name: String? = nullvar lastName: String?lastName = nullvar firstName: StringfirstName = null // Compilation error!!
Null II
Java
if(text != null){ int length = text.length();}
Kotlin
val length = text?.lengthval length = text!!.length // NullPointerException if text == null
Strings I
Java
String name = "John";String lastName = "Smith";String text = "My name is: " + name + " " + lastName;String otherText = "My name is: " + name.substring(2);
Kotlin
val name = "John"val lastName = "Smith"val text = "My name is: $name $lastName"val otherText = "My name is: ${name.substring(2)}"
Strings II
Java
String text = "First Line\n" + "Second Line\n" + "Third Line";
Kotlin
val text = """ |First Line |Second Line |Third Line""".trimMargin()
Ternary Operator
Java
String text = x > 5 ? "x > 5" : "x <= 5";
Kotlin
val text = if (x > 5) "x > 5" else "x <= 5"
BASICS
Bits Operations
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;
Kotlin
val andResult = a and bval orResult = a or bval xorResult = a xor bval rightShift = a shr 2val leftShift = a shl 2
Is As In
Java
if(x instanceof Integer){ }final String text = (String) other;if(x >= 0 && x <= 10 ){}
Kotlin
if (x is Int) { }val text = other as Stringif (x in 0..10) { }
Smart Cast
Java
if(a instanceof String){ final String result = ((String) a).substring(1);}
Kotlin
if (a is String) { val result = a.substring(1)}
Switch / When
Java
final int x = // value;final String xResult;switch (x){ case 0: case 11: xResult = "0 or 11"; break; case 1: case 2: //... case 10: xResult = "from 1 to 10"; break; default: if(x < 12 && x > 14) { xResult = "not from 12 to 14"; break; } if(isOdd(x)) { xResult = "is odd"; break; } xResult = "otherwise";}final int y = // value;final String yResult;if(isNegative(y)){ yResult = "is Negative";} else if(isZero(y)){ yResult = "is Zero";}else if(isOdd(y)){ yResult = "is Odd";}else { yResult = "otherwise";}
Kotlin
val x = // valueval xResult = when (x) { 0, 11 -> "0 or 11" in 1..10 -> "from 1 to 10" !in 12..14 -> "not from 12 to 14" else -> if (isOdd(x)) { "is odd" } else { "otherwise" }}val y = // valueval yResult = when { isNegative(y) -> "is Negative" isZero(y) -> "is Zero" isOdd(y) -> "is odd" else -> "otherwise"}
For
Java
for (int i = 1; i < 11 ; i++) { }for (int i = 1; i < 11 ; i+=2) { }for (String item : collection) { }for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in 1..10) { }for (i in 1..10 step 2) {}for (item in collection) {}for ((index, item) in collection.withIndex()) {}for ((key, value) in map) {}
Collections
Java
final List<Integer> numbers = Arrays.asList(1, 2, 3);final Map<Integer, String> map = new HashMap<Integer, String>();map.put(1, "One");map.put(2, "Two");map.put(3, "Three");// Java 9final List<Integer> numbers = List.of(1, 2, 3);final Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three");
Kotlin
val numbers = listOf(1, 2, 3)val map = mapOf(1 to "One", 2 to "Two", 3 to "Three")
Collections
Java
for (int number : numbers) { System.out.println(number);}for (int number : numbers) { if(number > 5) { System.out.println(number); }}
Kotlin
numbers.forEach { println(it)}numbers.filter { it > 5 } .forEach { println(it) }
Collections
Java
final Map<String, List<Integer>> groups = new HashMap<>();for (int number : numbers) { if((number & 1) == 0){ if(!groups.containsKey("even")){ groups.put("even", new ArrayList<>()); } groups.get("even").add(number); continue; } if(!groups.containsKey("odd")){ groups.put("odd", new ArrayList<>()); } groups.get("odd").add(number);}
Kotlin
val groups = numbers.groupBy { if (it and 1 == 0) "even" else "odd" }
Collections
Java
final List<Integer> evens = new ArrayList<>();final List<Integer> odds = new ArrayList<>();for (int number : numbers){ if ((number & 1) == 0) { evens.add(number); }else { odds.add(number); }}
Kotlin
val (evens, odds) = numbers.partition { it and 1 == 0 }
Collections
Java
final List<User> users = getUsers();Collections.sort(users, new Comparator<User>(){ public int compare(User user, User otherUser){ return user.lastname.compareTo(otherUser.lastname); }});// orusers.sort(Comparator.comparing(user -> user.lastname));
Kotlin
val users = getUsers()users.sortedBy { it.lastname }
二:Functions
Basic Function
Java
public void hello() { System.out.print("Hello, World!");}
Kotlin
fun hello() { println("Hello, World!")}
Arguments
Java
public void hello(String name){ System.out.print("Hello, " + name + "!");}
Kotlin
fun hello(name: String) { println("Hello, $name!")}
Default Values
Java
public void hello(String name) { if (name == null) { name = "World"; } System.out.print("Hello, " + name + "!");}
Kotlin
fun hello(name: String = "World") { println("Hello, $name!")}
Return
Java
public boolean hasItems() { return true;}
Kotlin
fun hasItems() : Boolean { return true}
Single-Expression
Java
public double cube(double x) { return x * x * x;}
Kotlin
fun cube(x: Double) : Double = x * x * x
FUNCTIONS
Vararg
Java
public int sum(int... numbers) { }
Kotlin
fun sum(vararg x: Int) { }
Main
Java
public class MyClass { public static void main(String[] args){ }}
Kotlin
fun main(args: Array<String>) {}
Named Arguments
Java
public static void main(String[]args){ openFile("file.txt", true);}public static File openFile(String filename, boolean readOnly) { }
Kotlin
fun main(args: Array<String>) { openFile("file.txt", readOnly = true)}fun openFile(filename: String, readOnly: Boolean) : File { }
Optional Arguments
Java
public static void main(String[]args){ createFile("file.txt"); createFile("file.txt", true); createFile("file.txt", true, false); createExecutableFile("file.txt");}public static File createFile(String filename) { }public static File createFile(String filename, boolean appendDate) { }public static File createFile(String filename, boolean appendDate, boolean executable) { }public static File createExecutableFile(String filename) { }
Kotlin
fun main(args: Array<String>) { createFile("file.txt") createFile("file.txt", true) createFile("file.txt", appendDate = true) createFile("file.txt", true, false) createFile("file.txt", appendDate = true, executable = true) createFile("file.txt", executable = true)}fun createFile(filename: String, appendDate: Boolean = false, executable: Boolean = false): File { }
Generic Methods
Java
public void init() { List<String> moduleInferred = createList("net");}public <T> List<T> createList(T item) { }
Kotlin
fun init() { val module = createList<String>("net") val moduleInferred = createList("net")}fun <T> createList(item: T): List<T> { }
Data Classes - Destructuring
Java
public static void main(String[]args) { Book book = createBook(); System.out.println(book); System.out.println("Title: " + book.title);}public static Book createBook(){ return new Book("title_01", "author_01");}public class Book { final private String title; final private String author; public Book(String title, String author) { this.title = title; this.author = author; } public String getTitle() { return title; } public String getAuthor() { return author; } @Override public String toString() { return "Title: " + title + " Author: " + author; }}
Kotlin
fun main(args: Array<String>) { val book = createBook(); // or val (title, author) = createBook() println(book) println("Title: $title")}fun createBook() : Book{ return Book("title_01", "author_01")}data class Book(val title: String, val author: String)
三:Classes
Constructor Call
Java
final File file = new File("file.txt");
Kotlin
val file = File("file.txt")
Class
Java
public final class User {}
Kotlin
class User
Open Class
Java
public class User {}
Kotlin
open class User
Final Attributes
Java
final class User { private final String name; public User(String name) { this.name = name; } public String getName() { return name; } }
Kotlin
class User(val name: String)
Primary Constructor
Java
final class User { private String name; public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Kotlin
class User(var name: String)
Optional Arguments in Constructors
Java
final class User { private String name; private String lastName; public User(String name) { this(name, ""); } public User(String name, String lastName) { this.name = name; this.lastName = lastName; } // And Getters & Setters }
Kotlin
class User(var name: String, var lastName: String = "")
Properties
Java
public class Document { private String id = "00x"; public String getId() { return id; } public void setId(String id) { if(id != null && !id.isEmpty()) { this.id = id; } } }
Kotlin
class Document{ var id : String = "00x" set(value) { if(value.isNotEmpty()) field = value }}
FUNCTIONS
Abstract Class
Java
public abstract class Document{ public abstract int calculateSize();}public class Photo extends Document{ @Override public int calculateSize() { }}
Kotlin
abstract class Document { abstract fun calculateSize(): Int}class Photo : Document() { override fun calculateSize(): Int { }}
Singleton
Java
public class Document { private static final Document INSTANCE = new Document(); public static Document getInstance(){ return INSTANCE; } }
Kotlin
object Document {}
Extensions
Java
public class ByteArrayUtils { public static String toHexString(byte[] data) { } } final byte[] dummyData = new byte[10]; final String hexValue = ByteArrayUtils.toHexString(dummyData);
Kotlin
fun ByteArray.toHex() : String {}val dummyData = byteArrayOf()val hexValue = dummyData.toHex()
Inner Class
Java
public class Documment { class InnerClass { }}
Kotlin
class Document { internal inner class InnerClass}
Nested Class
Java
public class Documment { public static class InnerClass { }}
Kotlin
class Document { class InnerClass}
Interface
Java
public interface Printable { void print();}public class Document implements Printable { @Override public void print() { }}
Kotlin
interface Printable{ fun print()}class Document : Printable{ override fun print() { }}
阅读全文
0 0
- Java 与 Kotlin 的语法对照
- kotlin 与 java 语法区别
- Kotlin&Java对照学习笔记
- Android java到Kotlin的基本语法
- kotlin 语法跟 java 的不同
- kotlin的基础语法
- Kotlin与Java的共存-Java中调用kotlin代码
- Kotlin与Java的共存-kotlin调用java代码
- kotlin基本语法与类型
- Kotlin第二章:Kotlin 的基本语法
- css与js语法对照
- CSDN-markdown编辑器简洁的语法与呈现效果对照
- pl/sql 与 mongo语法的对照表
- c# java语法对照表
- 心有Java,细嗅Kotlin —— 细数 Kotlin 优雅的语法糖
- Kotlin概述与Java的比较
- Kotlin与Java的使用区别
- Java与Kotlin的不同(一)
- Python协程(coroutine)
- 报错解决Context initialization failed org.springframework.beans.factory.BeanCreationException
- 机房练习赛hao 【Tsinghua OJ】祖玛(Zuma) (字符串)
- eclipse 项目jdk版本不一致导致的错误 Description Resource Path Location Type Target runtime com.genui
- error: Apostrophe not preceded by \ (in XXX.)
- Java 与 Kotlin 的语法对照
- bzoj2115 [ WC2011 ] -- 线性基
- H.264 码流格式: Annex-B, AVCC与extradata详解
- maven的两种可运行jar打包方式。1、内置依赖,2、外部依赖
- set集合
- Scrapy爬取1908电影网电影数据
- Java处理excel导入数据库日期格式的处理(24时制变为12时制问题的处理)
- 分页查询最后几页查不到
- JDBC笔记