val(value的简写)用来声明一个不可变的变量,这种变量在初始赋值之后就再也不能重新赋值,对应Java中的final变量。
var(variable的简写)用来声明一个可变的变量,这种变量在初始赋值之后仍然可以再被重新赋值,对应Java中的非final变量。
fun main() {
var a = 2
val b = "Hello Kotlin"
// val c = 12345678910l // compile error.
val c = 12345678910L // ok
val d = 3.0 // Double, 3.0f Float
val e: Int = 10
//val f: Long = e // implicitness not allowed
val f: Long = e.toLong() // implicitness not allowed
val float1: Float = 1f
val double1 = 1.0
val g: UInt = 10u
val h: ULong = 100000000000000000u
val i: UByte = 1u
println("Range of Int: [${Int.MIN_VALUE}, ${Int.MAX_VALUE}]")
println("Range of UInt: [${UInt.MIN_VALUE}, ${UInt.MAX_VALUE}]")
val j = "I❤️China"
println("Value of String 'j' is: $j") // no need brackets
println("Length of String 'j' is: ${j.length}") // need brackets
System.out.printf("Length of String 'j' is: %d\n", j.length)
val k = "Today is a sunny day."
val m = String("Today is a sunny day.".toCharArray())
println(k === m) // compare references.
println(k == m) // compare values.
val n = """
Hello World
Hello World
This is a demo page.
""".trimIndent()
println(n)
}
public class JavaBasicTypes {
public static void main(String... args) {
int a = 2;
final String b = "Hello Java";
long c = 12345678910l; // ok but not good.
long d = 12345678910L; // ok
int e = 10;
long f = e; // implicit conversion
// no unsigned numbers.
String j = "I❤️China";
System.out.println("Value of String 'j' is: " + j);
System.out.println("Length of String 'j' is: " + j.length());
System.out.printf("Length of String 'j' is: %d\n", j.length());
String k = "Today is a sunny day.";
String m = new String("Today is a sunny day.");
System.out.println(k == m); // compare references.
System.out.println(k.equals(m)); // compare values.
String n = "\n" +
"\n" +
"\n" +
" \n" +
" Hello World \n" +
"\n" +
"\n" +
" \n" +
" Hello World
\n" +
" This is a demo page.
\n" +
" \n" +
"\n" +
"";
System.out.println(n);
}
}
fun main() {
val a = IntArray(5)
println(a.size) //same with the Collections(e.g. List)
val b = ArrayList<String>()
println(b.size)
val c0 = intArrayOf(1, 2, 3, 4, 5)
val c1 = IntArray(5){ 3 * (it + 1) } // y = 3*(x + 1)
println(c1.contentToString())
val d = arrayOf("Hello", "World")
d[1] = "Kotlin"
println("${d[0]}, ${d[1]}")
val e = floatArrayOf(1f, 3f, 5f, 7f)
for (element in e) {
println(element)
}
e.forEach {
println(it)
}
if(1f in e){
println("1f exists in variable 'e'")
}
if(1.2f !in e){
println("1.2f not exists in variable 'e'")
}
}
import java.util.ArrayList;
public class JavaArrays {
public static void main(String... args) {
int[] a = new int[5];
System.out.println(a.length);// only array use 'length'
ArrayList<String> b = new ArrayList<>();
System.out.println(b.size());
int[] c = new int[]{1, 2, 3, 4, 5};
String[] d = new String[]{"Hello", "World"};
d[1] = "Java";
System.out.println(d[0] + ", " + d[1]);
float[] e = new float[]{1, 3, 5, 7};
for (float element : e) {
System.out.println(element);
}
for (int i = 0; i < e.length; i++) {
System.out.println(e[i]);
}
// Test in an Array
for (float element : e) {
if(element == 1f){
System.out.println("1f exists in variable 'e'");
break;
}
}
//Test not in an Array
boolean exists = false;
for (float element : e) {
if(element == 1.2f){
exists = true;
break;
}
}
if(!exists){
System.out.println("1.2f not exists in variable 'e'");
}
}
}
fun main() {
val intRange = 1..10 // [1, 10]
val charRange = 'a'..'z'
val longRange = 1L..100L
val floatRange = 1f .. 2f // [1, 2]
val doubleRange = 1.0 .. 2.0
println(intRange.joinToString())
println(floatRange.toString())
val uintRange = 1U..10U
val ulongRange = 1UL..10UL
val intRangeWithStep = 1..10 step 2
val charRangeWithStep = 'a'..'z' step 2
val longRangeWithStep = 1L..100L step 5
println(intRangeWithStep.joinToString())
val intRangeExclusive = 1 until 10 // [1, 10)
val charRangeExclusive = 'a' until 'z'
val longRangeExclusive = 1L until 100L
println(intRangeExclusive.joinToString())
val intRangeReverse = 10 downTo 1 // [10, 9, ... , 1]
val charRangeReverse = 'z' downTo 'a'
val longRangeReverse = 100L downTo 1L
println(intRangeReverse.joinToString())
for (element in intRange) {
println(element)
}
intRange.forEach {
println(it)
}
if (3.0 !in doubleRange) {
println("3 in range 'intRange'")
}
if (12 !in intRange) {
println("12 not in range 'intRange'")
}
val array = intArrayOf(1, 3, 5, 7)
for (i in 0 until array.size) {
println(array[i])
}
for(i in array.indices){
println(array[i])
}
}
fun main() {
val intList: List<Int> = listOf(1, 2, 3, 4)
val intList2: MutableList<Int> = mutableListOf(1, 2, 3, 4)
val map: Map<String, Any> =
mapOf("name" to "benny", "age" to 20)
val map2: Map<String, Any> =
mutableMapOf("name" to "benny", "age" to 20)
val stringList = ArrayList<String>()
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"])
// 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
}
import java.util.*;
public class JavaCollections {
public static void main(String... args) {
List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<String> stringList = new ArrayList<>();
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);
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("Hello", 10);
System.out.println(hashMap.get("Hello"));
}
}
有自己的类型,可以赋值、传递,并再合适的条件下调用
函数的引用类似C语言的函数指针,可用于函数传递
由于类型可以自动推断,所以可以不用写类型名
package com.bennyhuo.kotlin.builtintypes.functions
fun main(vararg args: String) {
println(args.contentToString())
val x:(Foo, String, Long)->Any = Foo::bar
val x0: Function3<Foo, String, Long, Any> = Foo::bar
// (Foo, String, Long)->Any = Foo.(String, Long)->Any = Function3
val y: (Foo, String, Long) -> Any = x
val z: Function3<Foo, String, Long, Any> = x
yy(x)
val f: ()->Unit = ::foo
val g: (Int) ->String = ::foo
val h: (Foo, String, Long)->Any
= Foo::bar
multiParameters(1, 2, 3, 4)
defaultParameter(y = "Hello")
val (a, b, c) = multiReturnValues() //伪
val r = a + b
val r1 = a + c
}
fun yy(p: (Foo, String, Long) -> Any){
//p(Foo(), "Hello", 3L)
}
class Foo {
fun bar(p0: String, p1: Long): Any{ TODO() }
}
fun foo() { }
fun foo(p0: Int): String { TODO() }
fun defaultParameter(x: Int = 5, y: String, z: Long = 0L){
TODO()
}
fun multiParameters(vararg ints: Int){
println(ints.contentToString())
}
fun multiReturnValues(): Triple<Int, Long, Double> {
return Triple(1, 3L, 4.0)
}
/**
* 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())
}