6-Kotlin Programming Language
6-Kotlin Programming Language
Programming Language
What is Kotlin?
• Statically typed
• JVM-targeted
• general-purpose
• programming language
• developed by JetBrains
lock (myLock) {
// Do something
}
fun lock(
theLock : Lock,
body : fun() : Unit
)
Implementation
• General: works everywhere, but costs
something
– Inner classes
– Method handles
• Special: may not work in some cases,
but costs nothing
– Inline functions
• Kotlin features both general and special
implementations
Lock example (III)
inline fun lock(
theLock : Lock,
body : fun() : Unit
) {
myLock.lock()
try {
body()
} finally {
myLock.unlock()
}
}
Extension function literals
• Extension functions
fun Int.f(p : Int) : String { return "…" }
• Extension function types
fun Int.(p : Int) : String
fun Int.(Int) : String
• Extension function literals
{Int.(p : Int) : String => "…"}
{Int.(p : Int) => "…"}
{Int.(p) => "…"}
HTML example (I)
• Function definition
fun html(init : fun HTML.() : Unit) : HTML {
val html = HTML()
html.init()
return html
}
• Usage
html {
this.addMeta(
httpEquiv="content-type",
content="text/html;charset=UTF-8")
}
HTML example (II)
• Function definition
fun html(init : fun HTML.() : Unit) : HTML {
val html = HTML()
html.init()
return html
}
• Usage
html {
addMeta(
httpEquiv="content-type",
content="text/html;charset=UTF-8")
}
Builders in Groovy
html {
head {
title "XML encoding with Groovy"
}
body {
h1 "XML encoding with Groovy"
p "this format can be used as an alternative markup to XML"
}
Builders in Kotlin: Implementation (III)
a (href="http://jetbrains.com/kotlin") { +"Kotlin" }
}
Foreach example (I)
inline fun <T> Iterable<T>.foreach(
body : fun(T) : Unit
) {
for (item in this)
body(item)
}
Example usage:
list map {it.length() > 2} foreach {
print(it)
}
Foreach example (II)
fun hasZero(list : List<Int>) : Boolean {
// A call to an inline function
list.foreach {
if (it == 0)
return true // Non-local return
}
return false
}