本文是根据慕课网kotlin相关课程本人笔记和个人理解所作
代码部分参考慕课网新kotlin入门课程
本来已经学习过好几次kotlin了,因为自己没有总结,工作中也没有用。所以决定总结一下,发一篇文章,后续会一直更新的,一起学习和进步!后面的demo是非常有意思的,函数是可以传递和保存的,简直不要太牛逼!!!
Kotlin | Java | |
---|---|---|
字节 | Byte | byte/Byte |
整型 | Int&Long | int/Integer&long/Long |
浮点型 | Float&Double | float/Float&double/Double |
字符 | Char | char/Character |
字符串 | String | String |
java
int a = 2;
final String b = "hello";
kotlin
var a:Int = 2
val b:String = "hello"
var a = 2
val b = "hello"
java
long c = 12345678910l;
long d = 12345678910L;
以上两种都可以但不推荐第一种
kotlin
var c = 12345678910l //compile error
var d = 12345678910L //ok
java
int e = 10;
long f = e;
上述代码正常运行
kotlin
var e:Int = 10
var f: Long = e //error
//正确写法
var e:Int = 10
var f: Long = e.toLong()
kotlin中所有的数值赋值都需要使用方法转换,不能直接赋值
java
String str = "kotlin";
System.out.print("I love " + str) ;
System.out.print("I love " + str.length()) ;
String n = "12345\n" +
"67890";
kotlin
var str = "kotlin"
print("I love $str ")
print("I love ${str.length}" )
print("I love %d",str.length )
var n = """
12345
67890
"""
Kotlin | Java | |
---|---|---|
整型 | IntArray | int[] |
整型装箱 | Array | Integer[] |
字符 | CharArray | char[] |
字符装箱 | Array | Character[] |
字符串 | Array | String[] |
java
int[] a = new int[5];
int[] a = new int[]{1,2,3,4,5};
List<String> a = new ArrayList<>();
kotlin
var a = IntArray(5)
var a = intArrayOf(1,2,3,4,5)
var a = IntArray(5){it + 1}
var a = ArrayList<String>()
java
for (int i = 0; i < e.length; i++){
print(e[i]);
}
kotlin
for (element in e){
print(element)
}
e.forEach(element ->
print(element))
e.forEach(
print(it))
java
for (int i = 0; i < e.length; i++){
if(e[i] == 1){
print(e[i]);
break;
}
}
kotlin
if (1 in e)
if (2 !in e)
kotlin
//.. 闭区间
val intRange = 1 .. 10
val charRange = 'a' .. 'z'
val longRange = 1L .. 10L
//until左闭右开
val intRangeE = 1 until 10
val charRangeE = 'a' until 'z'
val longRangeE = 1L until 10L
//downTo 闭区间倒序
val intRangeD = 10 downTo 1
val charRangeD = 'z' downTo 'z'
val longRangeD = 10L downTo 1L
//step
var intRange = 1 .. 10 step 2 //1 3 5 7 9
//for循环曲线救国
for (i in 0 until array.size){}
for (i in array.indices){}
Kotlin | Java | |
---|---|---|
不可变List | List | List |
可变List | MutableList | |
不可变Map | Map |
Map |
可变Map | MutableMap |
|
不可变Set | Set | Set |
可变Set | MutableSet |
java
List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<String> stringList = new ArrayList<>();
kotlin
val intList: List<Int> = listOf(1, 2, 3, 4)
val intList: MutableList<Int> = mutableListOf(1, 2, 3, 4)
val stringList = ArrayList<String>()
可变和不可变实质都是java的List
java
Map<String,Object> map = new HashMap<>();
kotlin
val map: Map<String, Any> = mapOf("name" to "benny", "age" to 20)
val map: Map<String, Any> = mutableMapOf("name" to "benny", "age" to 20)
java
for (int i = 0; i < 10; i++) {
stringList.add("num: " + i);
}
for (int i = 0; i < 10; i++) {
stringList.remove("num: " + i);
}
stringList.set(5, "HelloWorld");
String valueAt5 = stringList.get(5);
kotlin
for (i in 0 .. 10){
stringList.add("num: $i")
}
for (i in 0 .. 10){
stringList += "num: $i"
}
for (i in 0 .. 10){
stringList -= "num: $i"
}
stringList[5] = "HelloWorld"
val valueAt5 = stringList[5]
val hashMap = HashMap<String, Int>()
hashMap["Hello"] = 10
println(hashMap["Hello"])
kotlin
val pair = "Hello" to "Kotlin"
val pair = Pair("Hello", "Kotlin")
val first = pair.first
val second = pair.second
val (x, y) = pair
val triple = Triple("x", 2, 3.0)
val first = triple.first
val second = triple.second
val third = triple.third
val (x, y, z) = triple
class Foo {
fun bar(p0: String, p1: Long): Any{ TODO() }
}
fun foo() { }
fun foo(p0: Int): String { TODO() }
不写在类里
val f: ()->Unit = ::foo
val g: (Int) ->String = ::foo
val h: (Foo, String, Long)->Any = Foo::bar
class Foo {
fun bar(p0: String, p1: Long): Any{ TODO() }
}
val foo = Foo()
val m:(String, Long) -> Any = foo::bar
val x:(Foo, String, Long)->Any = Foo::bar
val x0: Function3<Foo, String, Long, Any> = Foo::bar
fun yy(p: (Foo, String, Long) -> Any){
p(Foo(), "Hello", 3L)
p.invoke(Foo(), "Hello", 3L)
}
java
void print(String... xxx){}
kotlin
fun print(vararg xxx:String){
xxx[]
}
kotlin
fun multiReturnValues(): Triple<Int, Long, Double> {
return Triple(1, 3L, 4.0)
}
kotlin
fun defaultParameter(x: Int = 5, y: String, z: Long = 0L){
TODO()
}
kotlin
defaultParameter(y = "Hello")
/**
* input: 3 * 4
*/
fun main(vararg args: String) {
if(args.size < 3){
return showHelp()
}
val operators = mapOf(
"+" to ::plus,
"-" to ::minus,
"*" to ::times,
"/" to ::div
)
val op = args[1]
val opFunc = operators[op] ?: return showHelp()
try {
println("Input: ${args.joinToString(" ")}")
println("Output: ${opFunc(args[0].toInt(), args[2].toInt())}")
} catch (e: Exception) {
println("Invalid Arguments.")
showHelp()
}
}
fun plus(arg0: Int, arg1: Int): Int{
return arg0 + arg1
}
fun minus(arg0: Int, arg1: Int): Int{
return arg0 - arg1
}
fun times(arg0: Int, arg1: Int): Int{
return arg0 * arg1
}
fun div(arg0: Int, arg1: Int): Int{
return arg0 / arg1
}
fun showHelp(){
println("""
Simple Calculator:
Input: 3 * 4
Output: 12
""".trimIndent())
}