对 Kotlin 的初步了解

引言

自从Google I/O 大会上宣布 Kotlin 成为 Android 开发的官方语言,Kotlin 就吸引了很多人的目光,笔者也收集了一些资料,整理成这篇博客来简单介绍下Kotlin。

Kotlin的起源:

Kotlin是一个基于JVM的新的编程语言,由JetBrains开发。JetBrains,作为目前广受欢迎的Java IDE IntelliJ的提供商,在Apache许可下已经开源其Kotlin编程语言。与Java相比,Kotlin的语法更简洁、更具表达性,而且提供了更多的特性,比如,高阶函数、操作符重载、字符串模板。它与Java高度可互操作,可以同时用在一个项目中。

接下来会从以下几个方面具体了解Kotlin

  1. Kotlin与Java语言上的比较;
  2. 使用 Kotlin 写一个Android demo;
  3. 尝试使用 Kotlin 代替 Java 完成服务端开发 ;

1. Kotlin与Java语言上的比较;

Kotlin相对Java主要有以下优势:

  • 函数式的:Kotlin是基于面向对象的语言。使用了很多函数式编程的概念,比如,使用lambda表达式来更方便地解决问题。其中一个很棒的特性就是Collections的处理方式。

函数式编程也是一个很火热的概念,具有一些比面向对象编程优秀的地方,建议可以去网上找资料了解一下。

  • 可以扩展函数:意味着我们可以扩展类的更多的特性,甚至我们没有权限去访问这个类中的代码。
    例如,以下代码可以更简单的使用Toast
 fun Activity.toast(message: CharSequence, duration: Int =  oast.LENGTH_SHORT){

    Toast.makeText(this, message, duration).show()
 }

  - Activity:表示函数的接收者,也就是函数扩展的对象
  - . :扩展函数修饰符
  - toast:扩展函数的名称
  - (...):扩展函数的参数,可以为null
  • 高度互操作性的:可以继续使用所Java写的代码和库,因为两
    个语言之间的互操作性是完美的。甚至可以在项目中使用Kotlin和Java混合编程。

我们可以轻松的使用 Intellij IDEA 自带的代码转换把Java代码转换为Kotlin代码

这里写图片描述

以转换ManActivity为例

package com.example.zz.kotlin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
package com.example.zz.kotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Kotlin 的文件是 .kt 结尾,向 .kt 文件中粘贴 Java 代码时都能自动转化为 Kotlin 代码,有点黑科技的意思。

这里写图片描述

Intellij IDEA 提供的十分贴心的转换代码功能,可以让初学者快速上手,同时也证明了 Kotlin 和 Java 兼容性良好。在熟悉 Kotlin 之后完全可以和 Java 混合开发。还有一个好处是 Kotlin 可以使用 Java 众多完善的框架,同时 Java 也可以使用 Kotlin 的优秀框架。所以 Kotlin 不仅是移动开发者需要关注的,JavaEE 开发者也可以把 Kotlin 作为第二语言掌握下来。

  • 更加易表现:Kotlin最重要的优点之一。开发相同功能你可以少写很多的代码。
    以下这个类是一个很常见的Java类,但是使用Kotlin可以节省很多代码量。
public class Student {
    private String name;//姓名
    private int age;//年龄
    private String hobby;//爱好

    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;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
}

使用Kotlin达到同样的效果只需要一行代码,而在Android开发中我们也不必在写烦人的findViewById了

class Student(var name: String, var age: Int, var hobby: String)
  • 更加安全:Kotlin是空安全的,就是说在编译时期就处理了各种null的情况,避免了执行时异常。如果一个对象可以是null,则我们需要明确地指定它,然后在使之前检查是否是null。可以节约很多调试nullPointException的时间并解决相应的bug。
//普通的 String 类型的变量不能为空
var str: String ="abc"
str = null //编译错误

-------------------------

//允许为空,我们必须把它声明为可空的变量:
var b: String? = "abc"
b = null

2.使用Kotlin写一个Android demo

Kotlin出自JetBrains之手,对Android Studio的自然是无缝支持。这一点也可以说是Kotlin的一个优势。毕竟一款好用的IDE可以极大的降低入手门槛。以下是使用Kotlin进行Android开发的一个实践。

  1. 安装 Kotlin 的插件
    这里写图片描述

  2. 配置gradle:
    在 Project 对应的 build.gradle 下添加以下有注释代码:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.0.2' //kotlin版本
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" //kotlin依赖

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在 Moudle 对应的 build.gradle 中添加下面的注释代码:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' //添加这行代码
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin' // 注明Kotlin路径
    }
    defaultConfig {
        applicationId "com.example.zz.kotlin"
        minSdkVersion 21
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" //直接使用build.gradle中的kotlin版本
    testCompile 'junit:junit:4.12'
}

注意不要直接复制粘贴,因为每个项目的路径和配置不一样

然后就可以愉快的使用 Kotlin 进行 Android 开发了

3.尝试使用 Kotlin 代替 Java 完成服务端开发

我们知道,Java 的核心优势其实是后端开发,JavaEE 有一系列完善的框架。而 Kotlin 号称能与 Java进行完全交互,那自然是要支持这些 Java 生态下的优秀框架,下面简单的用 Kotlin 整合 Spring + SpringMvc 来看看使用 Kotlin 对比 Java 有何区别

  1. 首先创建一个 Kotlin 项目,然后添加 Maven 组件
    这里写图片描述

这里写图片描述

  1. 然后添加 Spring 和 SpringMvc 的相关依赖,pom.xml文件如下:
<properties>
        <spring.version>4.2.5.RELEASE</spring.version>
        <jackson.version>2.7.3</jackson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- spring依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- jackson作为controller层的json转换器 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>
  1. 配置 spring 和 springmvc

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.kotlin">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
</beans>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <context:component-scan base-package="com.kotlin.controller" />
    <mvc:default-servlet-handler />
    <mvc:annotation-driven>
        <!-- json转换器 -->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                        <value>text/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
  1. 接下来做一个简单的 Controller 示例
    KotlinController的核心代码如下所示:
@RestController
class KotlinController {
    @Autowired
    private var kotlinService: KotlinService? = null

    @Autowired
    private var person: Person? = null

    @RequestMapping("/kotlin")
    fun home() = mapOf("kotlin" to kotlinService?.kotlin(), "map" to kotlinService?.map(), "person" to person)
}

KotlinService的核心代码如下:

@Service
class KotlinService {
    fun kotlin() = "kotlin"

    fun map() = mapOf("one" to 1, "two" to 2, "three" to 3)
}

Bean的核心代码如下:

@Component
data class Person(var name: String? = "xuwenhui", var id: Int? = 1)

可以看出,Kotlin 代替 Java 开发后端也相当简单,在熟悉语法之后就可以上手,而且可以继续使用 Java 的经典框架。同时,Kotlin 的一些新特性也让代码的简洁性和易读性有了一定程度的提高。

总结: 个人认为 Kotlin 是对 Java 某些地方的一些补充。比如,应用在移动开发领域可以充分发挥其语法简洁的优点。

以下是整理的一下学习Kotlin会用到的资料
官方文档
一个翻译的不错的中文文档

作者:张金龙
链接:对 Kotlin 的初步了解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值