Kotlin-Demo/test1/BasicSyntax.kt

118 lines
2.8 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package test1
fun main() {
println("Hello world!")
}
var x = 2
var y: Int = 2
val z: Int = 2
fun main(array: Array<String>) {
println(array.contentToString())
print("Hello ")
print("world!\n")
main()
println(42)
val sum = sum(1, 2)
println(sum)
val sum2 = sum2(1, 6)
println(sum2)
println("总和为:$sum and $sum2 那么sum和sum2相加为${sum + sum2}")
val basicSyntax = BasicSyntax(2.0000, 6.0)
println(basicSyntax.percent)
// 模板字符串
var a = 1
val b = "a 是 $a"
a = 2
val c = "${b.replace("是", "就是")}但是现在的a是 $a"
println(c)
// 返回最大值
println(BasicSyntax(1.0, 2.0).maxOf(1, 2))
println(BasicSyntax(1.0, 2.0).maxOf2(1, 2))
println(maxOf3(1, 2))
// 循环
val items = listOf("11", "22", "23", "24", "25")
for (item in items) {
println(item)
}
for (index in items.indices) {
println(index)
}
// 有多少元素
val readOnlyShapes = mutableListOf("triangle", "square", "circle")
println("readOnlyShapes有${readOnlyShapes.count()}个元素")
println("triangle" in readOnlyShapes)
// 添加元素
readOnlyShapes.add("YYY")
println(readOnlyShapes)
// 移出元素
readOnlyShapes.remove("triangle")
println(readOnlyShapes)
// Set相关操作
val readOnlyFruit = setOf("apple", "banana", "cherry", "cherry")
val mutableSetOf = mutableSetOf(readOnlyFruit)
println(readOnlyFruit)
println(mutableSetOf)
println("This set has ${readOnlyFruit.count()} items")
// map 操作
val readOnlyJuiceMenu = mapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(readOnlyJuiceMenu)
// {apple=100, kiwi=190, orange=100}
// Mutable map with explicit type declaration
val juiceMenu: MutableMap<String, Int> = mutableMapOf("apple" to 100, "kiwi" to 190, "orange" to 100)
println(juiceMenu)
val SUPPORTED = setOf("HTTP", "HTTPS", "FTP")
val requested = "smtp"
val isSupported = requested.uppercase() in SUPPORTED // Write your code here
println("Support for $requested: $isSupported")
val number2word = mapOf(1 to "one", 2 to "tow") // Write your code here
val n = 2
println("$n is spelt as '${number2word[2]}'")
}
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum2(a: Int, b: Int) = a + b
class BasicSyntax(height: Double, length: Double) {
val percent = (height + length) * 2
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
fun maxOf2(a: Int, b: Int): Int {
return if (a > b) {
a
} else {
b
}
}
}
/* The comment starts here
/* contains a nested comment */
and ends here. */
fun maxOf3(a: Int, b: Int) = if (a > b) a else b