和Flutter一样,Kotlin现在也很火,很多人愿意去学习尝试写Kotlin,有时知道Java语言该如何写就是不知道Kotlin语言的该如何下手,以此文记录一些Java转换为Kotlin的使用方法。
此文参考From Java to Kotlin,特此整理,用于自查。
每一个栗子,分割线上面是Java的写法,下面是Kotlin的写法。
System.out.print("Hello, World!"); System.out.println("Hello, World!"); ------------------------------------ print("Hello, World!") println("Hello, World!") 复制代码
final int x; final int y = 1; ---------------- val x: Int val y = 1 复制代码
int w; int z = 2; z = 3; w = 1; ----------- var w: Int var z = 2 z = 3 w = 1 复制代码
final String name = null; String lastName; lastName = null --------------------------------------- val name: String? = null var lastName: String? lastName = null var firstName: String firstName = null // Compilation error!! 复制代码
if(text != null){ int length = text.length(); } ------------------------------------------------------------------ val length = text?.length val length = text!!.length // NullPointerException if text == null 复制代码
String name = "John"; String lastName = "Smith"; String text = "My name is: " + name + " " + lastName; String otherText = "My name is: " + name.substring(2); ------------------------------------------------------ val name = "John" val lastName = "Smith" val text = "My name is: $name $lastName" val otherText = "My name is: ${name.substring(2)}" 复制代码
String text = "First Line/n" + "Second Line/n" + "Third Line"; ------------------------------- val text = """ |First Line |Second Line |Third Line """.trimMargin() 复制代码
String text = x > 5 ? "x > 5" : "x <= 5"; ----------------------------------------- val text = if (x > 5) "x > 5" else "x <= 5" 复制代码
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; ------------------------------ 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 复制代码
if(x instanceof Integer){ } final String text = (String) other; if(x >= 0 && x <= 10 ){} ----------------------------------- if (x is Int) { } val text = other as String if (x in 0..10) { } 复制代码
if(a instanceof String){ final String result = ((String) a).substring(1); } -------------------------------------------------- if (a is String) { val result = a.substring(1) } 复制代码
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"; } --------------------------------- val x = // value val 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 = // value val yResult = when { isNegative(y) -> "is Negative" isZero(y) -> "is Zero" isOdd(y) -> "is odd" else -> "otherwise" } 复制代码
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()) { } --------------------------------------------------------- for (i in 1 until 11) { } for (i in 1..10 step 2) {} for (item in collection) {} for ((index, item) in collection.withIndex()) {} for ((key, value) in map) {} 复制代码
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 9 final List<Integer> numbers = List.of(1, 2, 3); final Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three"); ---------------------------------------------------- val numbers = listOf(1, 2, 3) val map = mapOf(1 to "One", 2 to "Two", 3 to "Three") 复制代码
for (int number : numbers) { System.out.println(number); } for (int number : numbers) { if(number > 5) { System.out.println(number); } } ------------------------------- numbers.forEach { println(it) } numbers.filter { it > 5 } .forEach { println(it) } 复制代码
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); } // or Map<String, List<Integer>> groups = items.stream().collect( Collectors.groupingBy(item -> (item & 1) == 0 ? "even" : "odd") ); ------------------------------------------------------------------- val groups = numbers.groupBy { if (it and 1 == 0) "even" else "odd" } 复制代码
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); } } ---------------------------------------------- val (evens, odds) = numbers.partition { it and 1 == 0 } 复制代码
final List<User> users = getUsers(); Collections.sort(users, new Comparator<User>(){ public int compare(User user, User otherUser){ return user.lastname.compareTo(otherUser.lastname); } }); // or users.sort(Comparator.comparing(user -> user.lastname)); --------------------------------------------------------- val users = getUsers() users.sortedBy { it.lastname } 复制代码
public void hello() { System.out.print("Hello, World!"); } ------------------------------------ fun hello() { println("Hello, World!") } 复制代码
public void hello(String name){ System.out.print("Hello, " + name + "!"); } ------------------------------------------- fun hello(name: String) { println("Hello, $name!") } 复制代码
public void hello(String name) { if (name == null) { name = "World"; } System.out.print("Hello, " + name + "!"); } ------------------------------------------- fun hello(name: String = "World") { println("Hello, $name!") } 复制代码
public boolean hasItems() { return true; } --------------------------- fun hasItems() : Boolean { return true } 复制代码
public double cube(double x) { return x * x * x; } ------------------------------ fun cube(x: Double) : Double = x * x * x 复制代码
public int sum(int... numbers) { } ---------------------------------- fun sum(vararg x: Int) { } 复制代码
public class MyClass { public static void main(String[] args){ } } ------------------------------------------- fun main(args: Array<String>) { } 复制代码
public static void main(String[]args){ openFile("file.txt", true); } public static File openFile(String filename, boolean readOnly) { } ------------------------------------------------------------------ fun main(args: Array<String>) { openFile("file.txt", readOnly = true) } fun openFile(filename: String, readOnly: Boolean) : File { } 复制代码
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) { } ----------------------------------------------------------------------- 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 { } 复制代码
public void init() { List<String> moduleInferred = createList("net"); } public <T> List<T> createList(T item) { } -------------------------------------------------- fun init() { val module = createList<String>("net") val moduleInferred = createList("net") } fun <T> createList(item: T): List<T> { } 复制代码
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; } } -------------------------------------------------------- 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) 复制代码
final File file = new File("file.txt"); --------------------------------------- val file = File("file.txt") 复制代码
public final class User { } ------------------------- class User 复制代码
public class User { } ------------------- open class User 复制代码
final class User { private final String name; public User(String name) { this.name = name; } public String getName() { return name; } } ------------------------------ class User(val name: String) 复制代码
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; } } -------------------------------------- class User(var name: String) 复制代码
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 } ------------------------------------------------ class User(var name: String, var lastName: String = "") 复制代码
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; } } } ------------------------------------------- class Document{ var id : String = "00x" set(value) { if(value.isNotEmpty()) field = value } } 复制代码
public abstract class Document{ public abstract int calculateSize(); } public class Photo extends Document{ @Override public int calculateSize() { } } -------------------------------------- abstract class Document { abstract fun calculateSize(): Int } class Photo : Document() { override fun calculateSize(): Int { } } 复制代码
public class Document { private static final Document INSTANCE = new Document(); public static Document getInstance(){ return INSTANCE; } } ----------------------------------------------------------- object Document { } 复制代码
public class ByteArrayUtils { public static String toHexString(byte[] data) { } } final byte[] dummyData = new byte[10]; final String hexValue = ByteArrayUtils.toHexString(dummyData); -------------------------------------------------------------- fun ByteArray.toHex() : String { } val dummyData = byteArrayOf() val hexValue = dummyData.toHex() 复制代码
public class Documment { class InnerClass { } } ------------------------- class Document { inner class InnerClass } 复制代码
public class Documment { public static class InnerClass { } } -------------------------------------- class Document { class InnerClass } 复制代码
public interface Printable { void print(); } public class Document implements Printable { @Override public void print() { } } --------------------------------------------- interface Printable{ fun print() } class Document : Printable{ override fun print() { } } 复制代码
讲真,一顿复制粘贴操作下来,发现Kolin的写法真的简单很多。