在VS Code中使用Kotlin

在VS Code中使用Kotlin

 

当前Google有意用Kotlin来替代Java,今后在Android开发中,可能Kotlin会成为标准语言。

Kotlin语言是由JetBrains公司开发的,就是做IntelliJ IDEA的那家公司,Google的Android Studio也是基于IntelliJ IDEA改的。

我觉得Google打造一门新的Android开发语言是非常有必要的,现在Oracle公司在Java语言上的魔改已经使Java语言变得不伦不类了,那么何不重新来过呢,这样还不会有专利纠纷。更何况Kotlin是可以兼容Java的。

Kotlin语言在很多地方可以看到JavaScript函数式语言的特性,而且跟Java语言的差别也不是太大,它将会是一门好语言。

 

在VS Code中使用Kotlin比较简单,只需安装两个扩展即可:

1. Kotlin Language

2. Code Runner

在首次运行Kotlin程序时,终端中会出现乱码,这时可以在用户设置中添加一行:

"code-runner.runInTerminal": true

就能够解决终端乱码问题。

VS Code的当前版本把用户设置的默认界面改了,要点击如下按钮将界面恢复成之前的json文件形式:

修改用户配置

 

下面是Kotlin语言的一些语法特性演示:

package com.hanhf.demo;

val PI = 3.14 // const field
var x = 0 // normal field

// function
fun sum1(a: Int, b: Int): Int {
    return a + b
}

// simple function
fun sum2(a: Int, b: Int) = a + b

// function without return values, Unit is omitted
fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

// val vs var
fun lanDemo1() {
    val a: Int = 1
    val b = 2
    val c: Int
    c = 3
    x += 1
    var y = 5
    y += 1
}

// String
fun lanDemo2() {
    var a = 1
    val s1 = "a is $a"
    a = 2
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s2)
}

// if expression
fun maxOf(a: Int, b: Int) = if(a > b) a else b

// nullable return value
fun parseInt(str: String): Int? {
    return str.toIntOrNull();
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    if(x !=null && y != null) {
        println(x * y)
    } else {
        println("either $arg1 or $arg2 is not a number")
    }
}

// is
fun getStringLength1(obj: Any): Int? {
    if(obj is String) {
        return obj.length
    }
    return null
}

// !is
fun getStringLength2(obj: Any): Int? {
    if(obj !is String) return null
    return obj.length
}

// for
fun forDemo() {
    val items = listOf("apple", "banana", "kiwifruit")
    for(item in items) {
        println(item)
    }
}

// while
fun whileDemo() {
    val items = listOf("apple", "banana", "kiwifruit")
    var i = 0
    while(i < items.size) {
        println("item at $i is ${items[i]}")
        i++
    }
}

fun desc(obj: Any): String =
    when(obj) {
        1           -> "One"
        "Hello"     -> "Greeting"
        is Long     -> "Long"
        !is String  -> "Not a string"
        else        -> "Unknown"
    }

fun main(args: Array<String>) {
    /*
    var result1 = sum1(10, 20)
    println(result1)
    var result2 = sum2(30, 40)
    println(result2)
    printSum(50, 60)
    */
    // lanDemo2()
    /*
    printProduct("10", "abc")
    printProduct("10", "20")
    */
    // forDemo()
    // whileDemo()
    println(desc(2L))
}

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Kotlin编写的从相册获取图片并显示在ImageView的示例代码: 1. 在xml布局文件添加一个ImageView: ```xml <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="centerCrop" /> ``` 2. 在Activity添加以下代码: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var imageView: ImageView private val PICK_IMAGE_REQUEST = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) imageView = findViewById(R.id.imageView) imageView.setOnClickListener { pickImageFromGallery() } } // 从相册选择图片 private fun pickImageFromGallery() { val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(intent, PICK_IMAGE_REQUEST) } // 获取选择的图片并显示在ImageView override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) { val selectedImage = data.data val filePathColumn = arrayOf(MediaStore.Images.Media.DATA) val cursor = contentResolver.query(selectedImage!!, filePathColumn, null, null, null)!! cursor.moveToFirst() val columnIndex = cursor.getColumnIndex(filePathColumn[0]) val picturePath = cursor.getString(columnIndex) cursor.close() imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)) } } } ``` 以上代码通过点击ImageView触发从相册选择图片的操作,然后在onActivityResult方法获取并显示选择的图片。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值