class Person(firstName: String) {
}
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
class MyView : View {
constructor(ctx: Context) : super(ctx)
constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)
}
open class Base {
open fun v() {}
fun nv() {}
}
class Derived() : Base() {
override fun v() {}
}
class Address {
var name: String = ...
var street: String = ...
var city: String = ...
var state: String? = ...
var zip: String = ...
}
fun copyAddress(address: Address): Address {
val result = Address() // there's no 'new' keyword in Kotlin
result.name = address.name // accessors are called
result.street = address.street
// ...
return result
}
val simple: Int? // has type Int, default getter, must be initialized in constructor
val inferredType = 1 // has type Int and a default getter
var b: String? = "abc"
b = null // ok
val l = b.length // error: variable 'b' can be null
val l = if (b != null) b.length else -1
b?.length
val l = b?.length ?: -1
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}
fun reformat(str: String,
normalizeCase: Boolean = false,
upperCaseFirstLetter: Boolean = false,
divideByCamelHumps: Boolean = true,
wordSeparator: Char = '/') : String {..}
reformat(str,
normalizeCase = true,
upperCaseFirstLetter = true,
divideByCamelHumps = false,
wordSeparator = '_'
)
reformat(str, wordSeparator = '_')
fun double(x: Int) = x * 2
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.view.*
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
view.textView.setText("Hello, world!")
// Instead of findView(R.id.textView) as TextView
}
}
data class User(val name: String, val age: Int){
fun foo(): String {
....
}
}
class Delegate {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, thank you for delegating '${property.name}' to me!"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value has been assigned to '${property.name} in $thisRef.'")
}
}
println(e.p)
//Example@33a17727, thank you for delegating āpā to me!
e.p = "NEW"
//NEW has been assigned to āpā in Example@33a17727.
deck
By Petter Hdz
deck
- 348