Shawn qq:121857051
转载请留情
经过了近一个月的编写更新,我认为这篇文章给新手拿来入门应该算是可以了。
这70余个实例如果能挨个手码一遍,我相信任何新手都是能入门的吧。
学习一门编程语言,其实最重要的是英语水平(笑)。
如果你的英语水平还可以,其实大部分编程语言是可以不学习就能粗略读懂的。
当然,如果你有编程基础,了解基本的模式,那么学习一门语言的速度就可以更快,比如一个java程序员估计只用一个小时就能基本熟练使用Kotlin吧
这篇文章如果有任何错误、纰漏,请直接提出,我会及时更正。
https://blog.csdn.net/weixin_41084236/article/details/83308910
强烈推荐Kotlin官方文档
代码见github
注: 本文中实例部分参考于 runoobJava实例
fun main(args: Array<String>) {
var str : String = "Hello World"
var str1 : String = "Hello World"
var str2 : String = "hello World"
println(str.compareTo(str1))
println(str.compareTo(str2))
println(str.compareTo(str2,true))
println(str.equals(str1))
println(str.equals(str2))
println(str.equals(str2,true))
}
fun main(args: Array<String>) {
var str : String = "Hello, handsome boy."
var str1: String = "boy? I am not a boy!"
var lastHandsome : Int = str.lastIndexOf("handsome")
var lastBoy : Int = str.lastIndexOf("BoY",ignoreCase = true,startIndex = str.length)
var lastBoyInStr1 : Int = str1.lastIndexOf("boy",str1.length-5,true)
println("The last index of \"handsome\" is "+lastHandsome)
println("The last index of \"boy\" is "+lastBoy)
println("Now I ignore the last 5 chr in str1: "+lastBoyInStr1)
}
fun main(args: Array<String>) {
var str : String = "PHP, the best language."
println(removeCharAt(str,1))
}
fun removeCharAt(s:String,pos:Int): String{
return s.substring(0,pos)+s.substring(pos+1)
}
fun main(args: Array<String>) {
var str : String = "Shawn"
var strReversed : String = str.reversed()
println(str)
println(strReversed)
}
fun main(args: Array<String>) {
var str : String = "Python CPP Java Ruby Kotlin"
printPos(str.indexOf("python"))
printPos(str.indexOf("python",ignoreCase = true))
printPos(str.indexOf("Java"))
}
fun printPos(pos:Int){
if(pos == -1){
println("Do not find that string.")
}
else
{
println("Find that string in "+pos)
}
}
fun main(args: Array<String>) {
var str : String = "Shawn-handsome-python-best"
var splited : List<String> = str.split("-")
println(splited)
}
fun main(args: Array<String>) {
var str = "Shawn"
println(str.toUpperCase())
println(str.toLowerCase())
}
fun main(args: Array<String>) {
var str1 = "php Is the best."
var str2 = "who is your daddy?"
println(str1.regionMatches(4,str2,4,2))
println(str1.regionMatches(4,str2,4,2,true))
}
import java.util.*
fun main(args: Array<String>) {
var e = Math.E
System.out.format("%f%n",e)
System.out.format(Locale.CHINA, "%-10.4f%n%n", e)
}
fun main(args: Array<String>) {
var str1 = "No gods "
var str2 = "Or kings "
var str3 = "Only man!"
println(str1+str2+str3)
}
fun main(args: Array<String>) {
var array = intArrayOf(1,5,2,3,9,1)
print("Original: ")
printIntArray(array)
array.sort()
print("Sorted: ")
printIntArray(array)
println("'5' in the position: "+array.binarySearch(5))
}
fun printIntArray(intArray: IntArray){
for(i in intArray){
print(" "+i)
}
println()
}
fun main(args: Array<String>) {
var array = arrayListOf(1,2,3,4,"dog")
array.add(2.3)
array.add(true)
printArrayList(array)
}
public fun printArrayList(arrayList: ArrayList<out Any>):Unit{
for(i in arrayList){
println(i.toString())
}
}
fun main(args: Array<String>) {
var array : Array<Any> = Array<Any>(4,{9})
array.set(0,1)
array.set(1,"hop")
for(i in array){
println(i)
}
println("The length of array is "+array.size)
}
fun main(args: Array<String>) {
var array = arrayListOf<Any>(1,2,3,4,5)
array.reverse()
printArrayList(array)//from ArraysInsert.kt
}
fun main(args: Array<String>) {
var array = intArrayOf(2,3,1,6,-1,6,99)
println("The maximum of array is "+array.max())
println("The minimum of array is "+array.min())
}
fun main(args: Array<String>) {
var array1 : Array<String> = arrayOf("S","h","a")
var array2 : Array<String> = arrayOf("w","n")
var list = array1.asList()
list+=array2.asList()
println(list)
array1+=array2
printArray(array1)
}
public fun printArray(array:Array<out Any>){
for (i in array){
println(i)
}
}
fun main(args: Array<String>) {
var array = IntArray(6)
array.fill(2)
printIntArray(array)
}
fun main(args: Array<String>) {
var array = intArrayOf(1,2,3)
var arrayExtended = IntArray(5)
printIntArray(arrayExtended)
arrayExtended[3] = 4
arrayExtended[4] = 5
System.arraycopy(array,0,arrayExtended,0,array.size)
printIntArray(arrayExtended)
}
fun main(args: Array<String>) {
var array = intArrayOf(1,1,2,3,4,4,5,5,5,5,6,7,8,8,1,1,9,9)
var dup = ArrayList<Int>()
for (i in 0 until array.size-1){
for(j in i+1 until array.size){
if (array[i]==array[j] && !(array[i] in dup)){
println("Find duplicate: "+array[i])
dup.add(array[i])
}
}
}
}
fun main(args: Array<String>) {
var arrayList = ArrayList<String>()
arrayList.add("The first element")
arrayList.add("The second element")
arrayList.add("The third element")
arrayList.removeAt(1)
printArrayList(arrayList)
}
fun main(args: Array<String>) {
var arrayList1 = arrayListOf(1,2,2,3,4,4)
var arrayList2 = arrayListOf(1,2,5,3,3)
arrayList1.removeAll(arrayList2)
printArrayList(arrayList1)
}
fun main(args: Array<String>) {
var arrayList1 = arrayListOf("Shawn","Doge","Doge","XueBi","NiShiLong","NiShiLong")
var arrayList2 = arrayListOf("Shawn","Doge","Biu","WoShiLong","WoShiLong")
arrayList1.retainAll(arrayList2)
printArrayList(arrayList1)
}
fun main(args: Array<String>) {
var arrayList = arrayListOf(1,3,5,2,4,6,"DFWill","Boom!")
println("DFWill in the list? "+("DFWill" in arrayList))
println("1 in the list? "+arrayList.contains(1))
}
fun main(args: Array<String>) {
var array1 = intArrayOf(1,2,3,4)
var array2 = intArrayOf(1,2,3,4)
var array3 = intArrayOf(1,2)
println("array1 equals array2? "+array1.contentEquals(array2))
println("array1 equals array3? "+array1.contentEquals(array3))
}
fun main(args: Array<String>) {
var array1 = intArrayOf(1,2,2,3)
var array2 = intArrayOf(3,4,4,5)
var unionSet = emptySet<Int>()
unionSet+=array1.toSet()
unionSet+=array2.toSet()
printSet(unionSet)
}
public fun printSet(s:Set<out Any>){
for(i in s){
print(i.toString()+" ")
}
println()
}
import java.text.SimpleDateFormat
import java.util.*
fun main(args: Array<String>) {
val data = Date()
val dateFormat = "yyyy-MM-dd HH:mm:ss"
val simpleDateFormat = SimpleDateFormat(dateFormat)
println(simpleDateFormat.format(data))
}
class ClassInit constructor(info:String){
init{
println(info+" in the initializer block 1")
}
var str1 = "var str1".also(::println)
init{
println(info+" in the initializer block 2")
this.str1 = info
}
fun printstr1(){
println("str1: "+str1)
}
val str2 = "val str2".also(::println)
}
fun main(args: Array<String>) {
println("Begin")
var classInit = ClassInit("New")
var classInit2 = ClassInit("New2")
classInit.printstr1()
classInit2.printstr1()
}
class ClassSecondaryConstructor constructor(var name:String){
init{
println("Init block "+name)
}
var age = 0
var father = "father of ${name}".also(::println)
constructor(name:String,age:Int):this(name){
this.age = age
println("First secondary constructor "+name)
}
constructor(name:String,age:Int = 18,father:String):this(name,age){
this.father = father
println("Second secondary constructor "+name)
}
init{
println("Init block2 "+name)
}
}
fun main(args: Array<String>) {
var a = ClassSecondaryConstructor("Shawn")
var b = ClassSecondaryConstructor("XiaoMing",24)
var c = ClassSecondaryConstructor("Me",father = "Father")
}
open class Father{
public var age = 18
private var name = ""
constructor(name: String){
this.name = name
}
open public fun printName(){
println(name)
}
public fun printAge(){
println(age)
}
}
class Boy(name:String,age:Int):Father(name){
init{
this.age = age
}
override fun printName(){
super.printName()
println("from Boy")
}
}
fun main(args: Array<String>) {
var father = Father("Father")
var boy = Boy("Boy",5)
father.printName()
father.printAge()
boy.printName()
boy.printAge()
}
abstract class ClassAbstract(){
var i: Int? = null
abstract fun a()
abstract fun b()
}
interface ClassAbstractA{
fun a(i: Int):Int{
return i
}
}
interface ClassAbstractB{
fun b(s: String):String{
return s
}
}
class ClassAbstractClass:ClassAbstract(),ClassAbstractA,ClassAbstractB{
override fun a(){
println("a")
}
override fun a(i:Int):Int{
println("a"+i)
return i+1
}
override fun b(){
println("b")
}
override fun b(s: String): String {
println("b"+s)
return super<ClassAbstractB>.b(s)
}
}
fun main(args: Array<String>) {
var abstract = ClassAbstractClass()
abstract.a()
abstract.a(1)
abstract.b()
abstract.b("test")
}
fun main(args: Array<String>) {
var get = GetAndSet()
for(i in 0..5){
get.answer = i
println(get.answer)
}
}
class GetAndSet(){
var data = 0
var answer : Int
get() {
if(data!=0)return 42
else return data
}
set(value) {data = value%2}
}
fun main(args: Array<String>) {
var get = ClassField()
for(i in 0..5){
get.answer = i
println(get.answer)
}
}
class ClassField(){
var answer : Int = 0
set(value){
field = value-1
}
get() {
if(field==0)return 42
else return field
}
}
class ClassExtend{
var str: String?= null
}
fun ClassExtend.printStr(){
println(str)
}
fun ClassExtend.setStr(str:String){
this.str = str
}
fun main(args: Array<String>) {
var CE = ClassExtend()
CE.printStr()
CE.setStr("input something")
CE.printStr()
}
class ClassCompanion{
companion object {
fun printHello(){
print("Hello!")
}
val Dio: String = "Dio"
}
}
fun main(args: Array<String>) {
ClassCompanion.printHello()
print(" "+ClassCompanion.Dio)
}
enum class ClassEnum(val rgb:Int,var stuff:String){
RED(0xFF0000,"apple"){
override fun print() {
println(this.stuff)
}
},
GREEN(0x00FF00,"Your hat"){
override fun print() {
println("That is ok "+this.stuff)
}
},
BLUE(0x0000FF,"Sky"){
override fun print() {
println("I need some towers")
}
};
abstract fun print()
}
fun main(args: Array<String>) {
ClassEnum.RED.print()
ClassEnum.GREEN.print()
println(ClassEnum.BLUE.rgb)
println(ClassEnum.BLUE.stuff)
ClassEnum.BLUE.stuff = "Sea"
println(ClassEnum.BLUE.stuff)
}
data class ClassData(var aString: String,val bString: String){
init {
var sString = bString
}
fun print(){
println("Print in ${this.javaClass}")
}
}
fun main(args: Array<String>) {
var banana = ClassData("aBanana","bBanana")
var Banana = banana.copy(bString = "cBanana")
println(banana)
banana.print()
println(Banana)
Banana.print()
}
sealed class ClassSealed
data class SealedA(var seal:String):ClassSealed()
class SealedB:ClassSealed(){
fun print(){
println("I am a little seal.")
}
}
object SealedC:ClassSealed()
fun main(args: Array<String>) {
var list = listOf<ClassSealed>(SealedB(),SealedA("I am here for basking."),SealedC)
for (seal:ClassSealed in list){
when(seal){
is SealedA -> println(seal.seal)
is SealedB -> seal.print()
is SealedC -> println("And disappear again.")
}
}
}
fun main(args: Array<String>) {
var a = 1
var b = 2
if(a>b)
{
println(a)
}
else
{
println(b)
}
var max = if(a>b) a else b
println(max)
fun max(a:Int,b:Int) = when(a>b){
true -> a
false -> b
else -> null
}
fun isString(a:Any) = when(a){
is String -> println("That is a string")
!is String -> println("That is not a string")
else -> println("I have no idea")
}
println(max(233,666))
isString("Fish!")
}
fun main(args: Array<String>) {
var array = intArrayOf(1,2,3,4,5,6,7)
for(i in array) print(i)
println()
for(i:Int in array) print(i)
println()
for(i in 0..5) print(i)
println()
for(i in 0 until 5) print(i)
println()
for(i in 0 until 5 step 2)print(i)
println()
for(i in 5 downTo 0)print(i)
println()
for(i in 5 downTo 0 step 2) print(i)
}
fun main(args: Array<String>) {
loop@ for(i in 0..5){
loop2@ for(j in 6..10){
println(""+i+" and "+j)
if (i == 5) {
println("loop break")
break@loop
}
if (j == 9) {
println("loop2 continue")
continue@loop2
}
if ((i==0) and (j==7)) {
println("loop continue")
continue@loop
}
}
}
}
import java.lang.Exception
fun main(args: Array<String>) {
var list = intArrayOf(0)
for (i in 0..1){
try {
list[i] = 1 / i
println(list[i])
}catch(e: ArithmeticException){
e.printStackTrace()
}catch(e: ArrayIndexOutOfBoundsException){
e.printStackTrace()
}catch(e: Exception){
e.printStackTrace()
}finally {
println("Finally "+i)
}
}
}
class OperatorOverloadUnary(var i:Int){
operator fun unaryPlus():Int{
println("UnaryPlus: $i")
return i
}
operator fun unaryMinus():Int{
println("UnaryMinus: $i")
return i-1
}
operator fun not():Int{
println("not: $i")
return i-2
}
}
fun main(args: Array<String>) {
val i = OperatorOverloadUnary(9)
println(+i)
println(-i)
println(!i)
}
class OperatorOverloadIncAndDec(var i:Int){
init {
println("Here is $i")
}
override fun toString(): String {
return "toString: $i"
}
operator fun inc():OperatorOverloadIncAndDec{
println("INC $i")
return OperatorOverloadIncAndDec(i+10)
}
operator fun dec():OperatorOverloadIncAndDec{
println("DEC $i")
return OperatorOverloadIncAndDec(i-10)
}
}
fun main(args: Array<String>) {
var i = OperatorOverloadIncAndDec(42)
i++
i--
}
class OperatorOverloadBinary(var i: Int){
operator fun plus(j:Int){
println("plus $i and $j")
}
operator fun minus(s:String){
println("minus $i and $s")
}
operator fun times(j:Int){
println("times $i and $j")
}
operator fun div(j:Int){
println("div $i and$j")
}
operator fun rem(j:Int){
println("rem $i and $j")
}
operator fun rangeTo(s:String){
println("rangeTo $i and $s")
}
}
fun main(args: Array<String>) {
var i = OperatorOverloadBinary(9527)
i+1
i-"Banana"
i*3
i/4
i%5
i.."Banana!"
}
class OperatorOverloadAssign(var i: Int){
operator fun plusAssign(s:String){
println("plusAssign $i and $s")
}
operator fun minusAssign(i:Int){
println("minusAssign ${this.i} and $i")
}
operator fun timesAssign(s:String){
println("timesAssign $i and $s")
}
operator fun divAssign(i:Int){
println("divAssign ${this.i} and $i")
}
operator fun remAssign(s:String){
println("remAssign $i and $s")
}
}
fun main(args: Array<String>) {
var i = OperatorOverloadAssign(666)
i+="banana"
i-=2
i*="Banana"
i/=3
i%="Banana!"
}
class OperatorOverloadInvoke(var i: Int){
operator fun get(i:Int){
println("get ${this.i} and $i")
}
operator fun set(i:Any,j:Any){
println("set ${this.i} $i and $j")
}
operator fun invoke(i:Any){
println("invoke ${this.i} and $i")
}
}
fun main(args: Array<String>) {
var i = OperatorOverloadInvoke(233)
i[12]
i["banana"] = "Banana"
i("Banana!")
}
class OperatorOverloadLogic(var i: Int){
operator fun contains(i:Any):Boolean{
println("contains ${this.i} and $i")
return false
}
override fun equals(other: Any?): Boolean {
println("equals $i and $other")
return true
}
operator fun compareTo(i:Any):Int{
println("compareTo ${this.i} and $i")
return 42
}
}
fun main(args: Array<String>) {
var i = OperatorOverloadLogic(450)
println("banana" in i)
println(i == OperatorOverloadLogic(12))
println(i>1)
println(i<2)
println(i>=3)
println(i<="Banana")
}
/**
* This is a KDoc Demo
* *Here* you can write doc in a markdown way.
*
* @param KDoc a param of class KDoc
* @author Shawn
*/
class KDoc(var KDoc:String){
/**
* @property varA a property of [KDoc]
*/
var varA = 1
fun funA(paramA:String):String{
/**
* @param paramA a param of funA
* @return return the paramA
*/
return paramA
}
}
class ThreadNew : Thread(){
override fun run(){
super.run()
Thread.sleep(5000)
println("Hello")
}
}
fun main(args: Array<String>) {
val mThread = ThreadNew()
mThread.run()
}
fun main(args: Array<String>) {
val mRunnable = Runnable {
run {
Thread.sleep(3000)
println("Hello")
}
}
Thread(mRunnable).start()
}
class ComposeCall{
fun sayHi(){
println("Hi!")
}
fun sayHiToAny(any: Any){
println("Hi!"+any)
}
}
fun main(args: Array<String>) {
val hi = ComposeCall::sayHi
val composeCall = ComposeCall()
val arr = arrayOf("banana","Banana")
arr.forEach(::println)
arr.forEach(composeCall::sayHiToAny)
println(arr.filter(String::isNotEmpty))
println(hi)
println(ComposeCall::sayHiToAny)
}
fun main(args: Array<String>) {
val raw = listOf(1,2,3,3,3,3)
val newList = ArrayList<Int>()
raw.forEach {
newList.add(it+1)
}
println(newList)
println(raw.map{it*10})
println(raw.map(Int::toDouble))
}
fun main(args: Array<String>) {
val raw = listOf(
1..5,
99..101,
999..1002
)
println(raw)
println(raw.flatMap { it })
println(
raw.flatMap {
intRange -> intRange.map{
int -> "No.$int"
}
}
)
}
fun main(args: Array<String>) {
val list = listOf(5,9,10)
println(list.reduce{acc,i->acc*i})
}
fun main(args: Array<String>) {
val list = listOf(2,3,4,4,4)
println(list.fold(1,{acc, i -> acc*i }))
println(list.fold(StringBuilder(),{ acc, i -> acc.append(i) }))
}
fun main(args: Array<String>) {
val list = listOf(2,3,3,3,4,3,3)
println(list.filter { it == 3 })
println(list.filterIndexed { index, i -> index == i })
println(list.takeWhile { it < 4 })
}
class ComposeLet(val s1: String, val num: Int){
fun printS1(){
println(s1)
}
}
fun composeLet(i: Boolean):ComposeLet?{
if(i){
return ComposeLet("Banana",12)
}else{
return null
}
}
fun main(args: Array<String>) {
ComposeLet("banana",42).let {
println(it.s1)
it.printS1()
}
composeLet(true)?.let {
it.printS1()
}
composeLet(false)?.let {
println(it.num)
}
}
class ComposeWith(val s: String){
fun printS(){
println(s)
}
override fun toString(): String {
return s+" toString"
}
}
fun main(args: Array<String>) {
val result:String = with(ComposeWith("Banana")){
this.printS()
this.toString()
}
println(result)
}
class ComposeRun(val s: String, val s2: String){
fun printS(){
println(s)
}
}
fun composeRun(i:Boolean):ComposeRun?{
if (i){
return ComposeRun("Banana","yes!")
}else{
return null
}
}
fun main(args: Array<String>) {
val s = composeRun(true)?.run {
printS()
"This will be returned."
}
composeRun(false)?.run{
println("Do not work.")
}
println(s)
}
class ComposeApplyAndAlso(val s: String){
fun printS(){
println(s)
}
}
fun main(args: Array<String>) {
val apply = ComposeApplyAndAlso("apply banana").apply {
printS()
}
val also = ComposeApplyAndAlso("also banana").also {
it.printS()
}
println(apply)
apply.printS()
println(also)
also.printS()
}
fun tipsVarargs(vararg strings:String){
for(s in strings){
println(s)
}
for (i in 0 until strings.size){
print(strings[i]+" ")
}
}
fun main(args: Array<String>) {
tipsVarargs("banana","Banana","banana","banana")
}
fun main(args: Array<String>) {
var fruit = "banana"
val Fruit by lazy { fruit }
println(fruit)
fruit = "Banana"
println(Fruit)
}
const val TipsConst = "Only primitives and String are allowed"
class TipsGetClass
fun main(args: Array<String>) {
val tipsGetClass = TipsGetClass()
val cls = TipsGetClass::class.java
val kls = TipsGetClass::class
val tcls = tipsGetClass.javaClass
}
fun main(args: Array<String>) {
var a = TipsRefEqual("You")
var b = a
var c = a
var d = TipsRefEqual("You")
println(a==b)
println(b==c)
println(a==d)
println(a===b)
println(b===c)
println(a===d)
println(b===d)
}
class TipsRefEqual(var name:String){
override fun equals(other: Any?): Boolean {
return this.name==other.toString()
}
override fun toString(): String {
return this.name
}
}
class TipsInfix(var i: Int){
infix fun banana(i:Int){
println("infix banana ${this.i} and $i")
}
}
infix fun TipsInfix.poi(i:Int){
println("infix poi ${this.i} and $i")
}
fun main(args: Array<String>) {
var i = TipsInfix(12)
i banana 450
i poi 12
}
typealias StrArrayList = ArrayList<String>
typealias SAL = StrArrayList
fun main(args: Array<String>) {
var sal = SAL()
sal.add("banana")
sal.add("Banana")
var strArrayList = StrArrayList()
strArrayList.add("str")
strArrayList.add("Str")
println("The class of sal: "+sal.javaClass)
println("The class of strArrayList: "+strArrayList.javaClass)
}
class Outside{
var inside = Inside()
inner class Inside{
fun function(){
var outside = this@Outside
var inside = this@Inside
var func = this
println(outside.javaClass)
println(inside.javaClass)
println(func.javaClass)
}
}
}
fun Outside.func(){
println(this.javaClass)
}
fun main(args: Array<String>) {
var This = Outside()
This.Inside().function()
This.func()
}
fun TipsClosure(init: Int): (Int)->Unit{
var i = init
return fun(add: Int){
i+=add
println("here the i is: "+i)
}
}
fun main(args: Array<String>) {
val add = TipsClosure(42)
add(6)
add(6)
add(-11)
add(18)
}
fun main(args: Array<String>) {
val (a,b) = tipsComponent()
println(a.toString()+b)
}
data class TipsComponent(val res1: Int, val res2: String)
fun tipsComponent():TipsComponent{
return TipsComponent(23,"Banana")
}
fun main(args: Array<String>) {
val a = "banana"
val b: String? = null
println(a)
println(a?.length)
println(b)
println(b?.length)
try{
val c = b!!.length
}catch (NPE: NullPointerException){
NPE.printStackTrace()
}
}