• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

githubhaohao/JavaToKotlin: Java to Kotlin 语法清单

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

githubhaohao/JavaToKotlin

开源软件地址(OpenSource Url):

https://github.com/githubhaohao/JavaToKotlin

开源编程语言(OpenSource Language):

Kotlin 84.5%

开源软件介绍(OpenSource Introduction):

Java to Kotlin 语法清单

时刻对新事物保持好奇心

Google I/O 2017 宣布在 Android Studio 3.0 将默认支持 Kotlin 用于 Android 开发. 请注意 Google 只是宣布 Kotlin 作为 Android 开发的一级语言,并没有说要用其取代 Java ,这里很多无脑媒体进行了过度解读。作为一名合格的程序员,首先要理性看待技术迭代更新,同时要对新事物保持强烈的好奇心。

Kotlin 简介

Kotlin 来自于捷克一家牛逼软件研发公司 JetBrains ,很多优秀的 IDE,如 IntelliJ IDEA、PyCharm、WebStorm 等都是它的杰作,包括 Google 官方的 Android IDE -- Android Studio ,也是 IntelliJ IDEA 的插件版。

Kotlin 源于 JetBrains 的圣彼得堡团队,名称取自圣彼得堡附近的一个小岛 ( Kotlin Island ) ,JetBrains 在 2010 年首次推出 Kotlin 编程语言,并在次年将之开源。

Kotlin 的特点

Kotlin 是一个基于 JVM 的编程语言,与 Java 有很深的渊源。它能与 Java 100% 互通,具备诸多 Java 尚不支持的新特性。Kotlin 可以编译成 Java 字节码,也可以编译成 JavaScript ,方便在没有 JVM 的设备上运行,可用于移动端以及 Web 开发,是一种全栈式开发语言。

Java to Kotlin

下面是 Java to Kotlin 主要语法,以便于你快速认识 Kotlin 这门语言。

变量

Java

String lan = "Hello Kotlin";

final String lan = "Hello Kotlin";

Kotlin

var lan = "Hello Kotlin"

val lan = "Hello Kotlin"

打印字符串

Java

System.out.print("Hello Kotlin");

System.out.println("Hello Kotlin");

Kotlin

print("Hello Kotlin");

println("Hello Kotlin");

字符串模板

Java

String name = "haohao";

int age = 25;

String msg = "I am " + name + ", " + age + " years old.";

String text = "Hello Kotlin\n" +
              "Hello Android\n" +
              "Hello TensorFlow";

Kotlin

var name = "haohao";

var age = 25;

var msg = "I am $name , $age years old.";

var text = """
    |Hello Kotlin    
    |Hello Android
    |Hello TensorFlow
    """.trimMargin()
// trimMargin() 去除连接符 `|`

空声明

Java

String name = null;

Kotlin

var name: String? = null // `?` 声明变量可为 null 

判空

Java

if (name != null) {

    int len = name.length;
}

Kotlin

name?.let{

    val len = name.length
}

逻辑表达式

Java

String y = x > 6 ? "x > 6" : "x <= 6";

Kotlin

var y = if (x > 6)
            "x > 6"
        else "x <= 6"

类型判断及转换

Java

if (obj instanceof Person) {

    Person p = (Person) obj;
}

Kotlin

if (obj is Person) {

    var p = obj //智能转换
}

区间

Java

if (value >= 0 && value <= 100) {
}

for (int i = 1; i <= 100 ; i++) {}

for (int i = 1; i < 100 ; i++) {}

for (int i = 100; i >= 0 ; i--) {}

for (int i = 1; i <= 100 ; i+=2) {}

for (int i = 100; i >= 0 ; i-=2) {}

Kotlin

if (value is 0..100) {
}

for (i in 1..100 ) {}

for (i in 1 until 100) {} // 半开区间:不包含 100

for (i in 100 downTo 0) {}

for (i in 1..100 step 2) {}

for (i in 100 donwTo 1 step 2) {}

list 和 map ( 针对 Java 8 之前版本 )

Java

List<Integer> list = Arrays.asList(1, 2, 3, 4);

for(Integer value : list) {

   System.out.println(value);
}

Map<Integer, String> map = new HashMap<>();

map.put(1, "Java");

map.put(2, "Kotlin");

map.put(3, "iOS");

map.put(4, "React Native");


Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();

while (iterator.hasNext()) {

    Map.Entry<Integer, String> entry = iterator.next();

    System.out.println(entry.getKey() + " , " + entry.getValue());
}

Kotlin

var list = listOf(1, 2, 3, 4);

list.forEach {

   println(it)
}

var map = mapOf(1 to "Java", 2 to "Kotlin", 3 to "iOS", 4 to "React Native")

map.forEach { key, value ->

    println("$key, $value")
}

// 或者

for ((key, value) in map) {

    println("$key, $value")
}

开关语句

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"

	in 1..3 -> "Fail"

	else -> "Fail"
}

流水线

Java

List<String> list = Arrays.asList("java", "c++", "Android", "Kotlin", "iOS");

for(int i = 0; i < list.size(); i++ ) {

    list.set(i, "Hello " + list.get(i));

    if (!list.get(i).contains("c")) {

        System.out.println(list.get(i));
    }
}

//输出:
//    Hello java
//    Hello Android
//    Hello Kotlin
//    Hello iOS

Kotlin

var list = arrayOf("java", "c++", "Android", "Kotlin", "iOS")

list.map {

    "Hello $it"

}.filter {

    !it.contains("c")

}.forEach {

    println(it)

}

//输出:
//    Hello java
//    Hello Android
//    Hello Kotlin
//    Hello iOS

函数

Java

public final void func() {}

public final int func(int value) {

    return 1 * value;
}

Kotlin

fun func() {}

fun func(value: Int): Int {

    return 1 * value
}

// 或者

fun func(value: Int): Int = 1 * value

Java

public final class Person {

    private String name = null;

    private int age = 25;

    private Person() {
    }

    public Person(String name, int age) {

        this.name = name;
        this.age = age;
    }
}

Kotlin

class Person private constructor() {

    private var name: String? = null

    private var age: Int = 25
    
    constructor (name: String, age: Int): this() {

        this.name = name
        this.age = age
    }
}

静态方法( 伴生对象 )

Java

public final class Manager {

    private Manager() {}

    public static Manager getInstance () {

        return new Manager();
    }
}

Kotlin

class Manager private constructor() {

    companion object {

        fun getInstance(): Manager = Manager()
    }
}

实体类

Java

public class Person {

    public String name;

    public age;

    public Person(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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != person.age) return false;
        return name != null ? name.equals(person.name) : person.name == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Kotlin

data class Person(var name: String, var age: Int)

解构

Java

Person p = new Person("haohao", 25);

String name = p.getName();

String age = p.getAge();

Kotlin

var p = Person("name", 25)

var (name, age) = p

接口

Java

interface Readable {

    String getContent();
}
public final class Book implements Readable {

    @override
    public String getContent() {

        return "Hello";
    }
} 

Kotlin

// Kotlin 接口中可以设置抽象和非抽象方法,可以有属性但必须声明为抽象或提供访问器实现。
interface Readable {

   fun getContent(): String

   fun getVersion(): Int = 0 
   
}
class Book(): Readable {

   override fun getContent(): String = "Hello"
   
   override fun getVersion(): Int {

       return super.getVersion()
   }
}

继承

Java

public class Person {
 
    private String name = null;

    public Person(String name) {
        this.name = name;
       
    }

    public void sayHello() {
        System.out.println("Hello");
    }

    public final void sayGood() {
        System.out.println("Good");
    }

}
public final class Student extends Person {

    private String school = null;

    public Student(String name, String school) {
        super(name);
        this.school = school;
    }

    @Override
    public void sayHello() {
        super.sayHello();
        System.out.println("Hello Student");
    }
}

Kotlin

open class Person(private var name: String? = null) {

    open fun sayHello() = println("Hello")

    fun sayGood() = println("Good")

}
class Student(private var school: String? = null, name: String): Person(name) {
    
   override fun sayHello() {
       super.sayHello()
       println("Hello Student")
   }
    
} 

静态与非静态内部类

Java

public final class Outer {

    private int bar = 100;
    
    public static class Nester {
         
        public final String foo() {
            return "Hello Kotlin!";
        }
    }

    public final class Inner {
    
        public final int foo() {
            return bar; // 可以访问外部类成员
        }
        
    }
    
}


System.out.println(new Outer.Nester().foo()); 

// System.out.println(new Outer().Inner().foo()); 不能在其他类中实例化非静态内部类

Kotlin


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap