Professional Documents
Culture Documents
Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
var column:Int
Returning Tuple //---numbers3 has now 10 elements )
fun countNumbers(string:String): // all 0s var stone1 = Go(12,16)
Pair<Int,Int>{ var numbers3 = IntArray(10) with(stone1) {
var odd = 3 // same as int[] in Java row = 9
var even = 4 column = 13
// do something //---numbers3 has now 10 elements }
return Pair(odd, even) // from 0 to 9
} numbers3 =
intArrayOf(0,1,2,3,4,5,6,7,8,9) Looping
val count = countNumbers("12345") // prints 0 to 4
// numbers4 has now 10 elements var count = 0
while (count < 5) {
Default Parameter Value // {0,1,4,9,16,25,...}
val numbers4 = IntArray(10) { print (count)
fun join(firstName:String, n -> n*n count += 1
lastName:String, } }
joiner:String=" "):String {
return $firstName$joiner$lastName" // prints 0 to 4
} The it Keyword count = 0
// same as numbers4 repeat (5) {
var fullName = val numbers5 = IntArray(10) { print(count)
join("Wei-Meng", "Lee", ",") it*it count += 1
// Wei-Meng,Lee // "it" is the implicit }
// name of the single parameter
fullName = join("Wei-Meng", "Lee") } // prints 0 to 4
// Wei-Meng Lee for (i in 0..4) {
print(i)
Dictionaries
Variable Arguments val platforms1 = hashMapOf(
}
fun average(vararg nums:Int):Float { "Apple" to "iOS",
var sum: Float = 0F "Google" to "Android", Classes
for (num in nums) { "Microsoft" to "Windows Phone" class MyLocation {
sum += num.toFloat() ) }
}
return sum/nums.size val p1 = platforms1["Apple"] // type inference
} //---"iOS"--- val loc1 = MyLocation()
var avg = average(1,2,3,4,5,6) val p2 = platforms1["Samsung"] // declare and initialize
// 3.5 //---null--- val loc2:MyLocation = MyLocation()
// error }
print("Undefined") Properties
// items[3] = 9 // list is immutable class MyLocation {
// all properties must be
// mutable (dynamic) Matching Range // initialized
var wishes: MutableList<String> = var percentage: Int = 85 // var for read/write properties
mutableListOf() when (percentage) { var lat:Double? = null
wishes.add("iPhone") in 0..20 -> var lng:Double? = null
wishes.add("iPad") print("Group 1")
in 21..40 -> // val for read-only properties
val arrived:Boolean = false
Array<Int> vs IntArray print("Group 2")
in 41..60 -> }
// declare; numbers0 is now null print("Group 3")
val numbers0: Array<Int> in 61..80 -> val loc = MyLocation()
// same as Integer[] in Java print("Group 4") loc.lat = 57.474392
in 81..100 -> loc.lng = 37.228008
// declare and init; numbers1 now print("Group 5") print(loc.arrived)
// has 10 elements else ->
var numbers1: Array<Int> =
arrayOf(0,1,2,3,4,5,6,7,8,9) }
print("Invalid percentage") Primary Constructor
// primary constructor
// same as numbers1 class MyLocation (var lat:Double,
var numbers2= Data Class var lng:Double) {
arrayOf(0,1,2,3,4,5,6,7,8,9) data class Go ( val arrived:Boolean = false
var row:Int,
Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
fun someMethod() {
val latitude = this.lat var loc5 = MyLocation() Lambda Functions
val longitude = this.lng loc5.lat = 157.474392 // exception //---Button view---
} loc5.lng = 37.228008 val btnOpen =
} print(loc5.arrived) findViewById<Button>(R.id.btnOpen)
Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.
items[i+1])) { {
val temp = items[i+1] Instance Methods return (2 * Math.PI *
items[i+1] = items[i] class Car { radius).toFloat()
items[i] = temp var speed = 0 }
swapped = true fun accelerate() { }
} }
} fun decelerate() { var c = Circle(6F)
if (!swapped) break } area = c.area() // 28.274334
} fun stop() { perimeter = c.perimeter()
return items } // 18.849556
} fun printSpeed() { perimeter = c.perimeter(5F)
} // 31.415926
val numbers = }
intArrayOf(5,2,8,7,9,4,3,1)
val c = Car() Extensions
// ascending order c.accelerate() // extending the Context class with
var sortedNumbers = bubbleSort( c.decelerate() // the displayToast() function
numbers, { num1, num2 -> c.stop() fun Context.displayToast(
num1 < num2 } ) c.printSpeed() text:CharSequence,
duration:Int=Toast.LENGTH_SHORT) {
// descending order Toast.makeText(this, text,
sortedNumbers = bubbleSort( Companion Object (Static duration).show()
}
numbers, { num1, num2 ->
num1 > num2 } )
Method/Variable) // without extension
class Car { Toast.makeText(this,
companion object { "Hello, Kotlin",
// another way of passing in the
val MilesToKM = 1.60934 Toast.LENGTH_SHORT).show()
// lambda function
fun kilometersToMiles( // with extension
sortedNumbers = bubbleSort(numbers)
km:Float):Double { displayToast("Hello, Kotlin!")
{ num1, num2 -> num1 < num2 }
return km / 1.60934
}
Property Observers }
fun String.LatLng(splitter:String):
class MyPointClass { fun accelerate() {}
Pair<Float, Float> {
var x: Int by fun decelerate() {}
val latlng = this.split(splitter)
Delegates.observable(0) { fun stop() {}
return Pair(latlng[0].toFloat(),
prop, old:Int, new:Int -> fun printSpeed() {}
latlng[1].toFloat())
println(prop.name + }
}
" : from $old to $new") val v = Car.MilesToKM
var str = "1.23456,103.345678"
} val miles =
var latlng = str.LatLng(",")
} Car.kilometersToMiles(10F)
print(latlng.first)
print(latlng.second)
val pt = MyPointClass()
pt.x = 5 // x : from 0 to 5
Final Class
pt.x = 6 // x : from 5 to 6
// by default, all the classes in
// Kotlin are final (non-
Interfaces
interface CarInterface {
// inheritable)
fun accelerate() {
Vetoable Property class ClosedClass {
}
// default implementation
class MyPointClass { }
var x: Int by // error
fun decelerate()
Delegates.vetoable(0) { class Subclass0:ClosedClass() { fun accelerateBy(amount:Int)
prop, old:Int, new:Int -> } }
println(prop.name +
" : from $old to $new")
new > 0
Overriding and class MyCar:CarInterface {
override fun accelerate() {
} Overloading Methods // override implementation in
} open class Shape(length:Float, // interface
width:Float) { }
val pt = MyPointClass() var length:Float override fun decelerate() {
pt.x = 5 // x : from 0 to 5 var width:Float }
pt.x = 6 // x : from 5 to 6 init { override fun accelerateBy(amount:
pt.x = 0 // x will roll back to 6 this.length = length Int) {
this.width = width }
} }
Identity Operator open fun perimeter():Float {
class MyPointClass {
var x = 0 }
return 2 * (length + width)
Generic Class
var y = 0 open fun area(): Float { class MyStack<T> {
return length * width val elements:MutableList<T> =
constructor(x:Int, y:Int) { } mutableListOf()
this.x = x } fun push(item:T) {
this.y = y elements.add(item)
} class Circle(diameter:Float): }
} Shape(diameter / 2, diameter / 2) fun pop():T? {
var pt1 = MyPointClass(5,6) { if (elements.size>0) {
var pt2 = pt1 override fun area():Float { return elements.removeAt(
var pt3 = MyPointClass(5,6) return (Math.PI * elements.size-1)
if (pt1 === pt2) { this.length.pow(2F)).toFloat() } else {
print("Identical") } return null
} else { }
print("Not identical") override fun perimeter(): Float { }
} // Identical return (2 * Math.PI * }
if (pt1 === pt3) { this.length).toFloat() var item = myStringStack.pop()
print("Identical") } // kotlin
} else { item = myStringStack.pop()
print("Not identical") // overloading // programming
} // Not identical fun perimeter(radius:Float): Float item = myStringStack.pop() // null
Rev 1.3.1 © Wei-Meng Lee , Developer Learning Solutions, http://calendar.learn2develop.net All rights reserved.