Kotlin öğreniyorum ,Lambdas, Modifiers,Null kontrol— Part 4

Buse Tekin Aydın
Sep 6, 2018 · 2 min read

Lambdas

Örnek bir setOnClickListener methodunun lambda ile yazılışı:

Normali

view.setOnClickListener(object : OnClickListener {    override fun onClick(v: View) {       toast("Click") // bu toast mesajı Anko'dan    }})

Lambda kullanarak :

fun setOnClickListener(listener: (View) -> Unit)

Burda ok ‘un sol tarafı fonksiyona girecek inputu sağ tarafı return type’ı gösterir. Yani ;

(View) =function input arguments

Unit = return type ( nothing)

view.setOnClickListener({ view -> toast(“Click”)})

Niteliyiciler(Modifiers)

private — tanımlandığı dosyada görünebilir

public — heryerde görünebilir

internal — aynı modülde görünebilir ( kendiyle derlenen dosyalar diyebiriz)

protected — kendi sınıfında ve ondan türeyen sınıflarda görünebilir.

Örnek :

open class Outer {
private val a = 1
protected open val b = 2
internal val c = 3
val d = 4 // public olarak tanımlanır defaultta

protected class Nested {
public val e: Int = 5
}
}
class Subclass : Outer() {
// a görünür değil , çünkü private subclassta görünmez
// b, c ve d görünür,çünkü protected subclassta internal aynı modülde görünebilirdir,public heryerde görünür
// Nested ve e görünür protected ve public olduğu için
override val b = 5 // ‘b’ protected
}
class Unrelated(o: Outer) {
// o.a, o.b görünür değil, çünkü farklı bir class içerisinden ulaşmaya çalışıyoruz
// o.c ve o.d görünür
// Outer.Nested ve Nested::e görünür değil
}
örnek kaynak = https://kotlinlang.org/docs/reference/visibility-modifiers.html

internal ve public arasındaki farkı anlamak isteyenler şu yorumu inceleyebilir.

Delegated property

Sık kullanılan fonsiyonları gruplayabiliriz.Örneğin getter ve setter methodları gibi.Kodu tekrar tekrar yazmaktan kurtuluruz.

örnek:

class Delegate<T> {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
return..
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
}
}

Aggregate operations

val list = listOf(1, 2, 3, 4, 5, 6)

list.forEach { println(it) }

Kotlinde Null kontrolü

val a: Int? = nulla?.toLong()

Burada a?. ile null değilse toLong() işlemini yapmasını sağladık.

?. buna safe call operator denir.

Diğer bir alternatif Elvis operator (?:) kullanmak:

val myLong = a?.toLong() ?: return falseval myLong = a?.toLong() ?: throw IllegalStateException()

Burada ise myLong ‘a gelen değer a null değilse a.toLong() , null ise false.

Şimdilik burda bırakalım.

Buse Tekin Aydın

https://github.com/busetekin

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade