Kotlin etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Kotlin etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

20 Ağustos 2021 Cuma

Kotlin run function

Giriş
Açıklaması şöyle
Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.

Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.
There are a few scope functions
- let
- with
- run
- apply
- also
run metodu
run() metodunun iki tane hali var. Açıklaması şöyle
run has two variants, one is an extension function to Template class and another one is not an extension function to Template class.
Extension Function
Örnek
Şöyle yaparız
class Employee {
    var firstName: String? = null
    var age: Int = 0
}

val employee: Employee? = Employee()
employee?.firstName = "Suneet"
employee?.age = 27

employee?.run {
    println(age)
}
Not Extension Function
Örnek
Şöyle yaparız
val alphaNumeric = run {
val digits = "0-9" val aplhabets = "A-Za-z" Regex("[$digits$aplhabets]+") } for (match in alphaNumeric.findAll("+1234 -FFFF I-am?-a!string?!")) { println(match.value) } //this will print 1234 FFFF I am a string


10 Ağustos 2021 Salı

Kotlin Modifiers

Giriş
Açıklaması şöyle
Kotlin has the following visibility modifiers: public, protected, private and internal. internal modifier means that the member is visible within the same module (For e.g. Gradle module, IntelliJ IDEA module, etc). This means other Kotlin modules can’t access classes/members marked with an internal modifier. This feature of Kotlin is helpful in a way such that you can easily access, modify and test the internal functionalities or properties of a module

6 Ağustos 2021 Cuma

Kotlin Single Expression

Return Type Otomatik Bulunur
Örnek
Şöyle yaparız. Return Type derleyici tarafından bulunabilir
fun getItemById(id: String) = repository.findItemById(id)
Return Type Belirtme
Return type kodda belirtilebilir.
Örnek
Şöyle yaparız
fun getItemById(id: String): Item = repository.findItemById(id)
Bir Şey Return Etmeyen Expression
Örnek
Elimizde şöyle bir kod olsun
fun greetGoodMorning() {
  // Some code
  println("Good Morning")
}

fun greetGoodAfternoon() = {
  // Some code
  println("Good Afternoon")
}

fun main() {
  greetGoodMorning()
  greetGoodAfternoon()
}

// Output:
// Good Morning
Burada return type lambda block olarak algılanıyor. Yani şöyle. Lambda çağrılmadığı için de çalışmıyor
fun greetGoodAfternoon(): () -> Unit = {
  // Some code
  println("Good Afternoon")
}



30 Temmuz 2021 Cuma

Kotlin Null Kontrolü

Giriş
1. Nullable Type
Açıklaması şöyle. C# ile aynı aslında
?: literally means “if the left part is null, call or return right part”.
Örnek
Şöyle yaparız
fun func(obj : MyClass?) {
 obj?.c?.printClass() : print("oops");
}
2. requireNotNull ve checkNotNull kullanılır.
Açıklaması şöyle
requireNotNull can throw an IllegalArgumentException while checkNotNull can throw an IllegalStateException
Farkları şöyle
It is a semantic difference and hence it throws different exceptions. RequireNotNull is used to check input values, typically at the beginning of a method, while checkNotNull is used anywhere to check the current state.
requireNotNull şöyle
[...]
if (value == null) {
    val message = lazyMessage()
    throw IllegalArgumentException(message.toString())
} else {
    return value
}
checkNotNull şöyle
[...]
if (value == null) {
    val message = lazyMessage()
    throw IllegalStateException(message.toString())
} else {
    return value
}

28 Temmuz 2021 Çarşamba

Kotlin let Anahtar Kelimesi

Açıklaması şöyle
let is treated as a native way to do null checks on the variables.

Please don’t do that even if using `let` feels functionally beautiful but

- You will end up creating another reference called it in the same scope which is less descriptive
- To fix that you will definitely try to provide an explicit parameter for lambda example imageFile?.let{ image →,
- but it creates a load of finding another name for the same variable (naming things are hard)
- Now other devs can refer to image files in the scope with two names imageFile and image, with time you need to maintain that the right variable is being used inside the scope of lambda when there is iteration over the code for bugs and changes.
Örnek - null check
Birinci maddeyi gösteren bir kod şöyle
fun deleteImage(){
   var imageFile : File ? = ...
   imageFile?.let { // ❌ don't write code like this
      if(it.exists()) it.delete()
   }
}
Bu yöntem illaki kullanılacaksa "it" yerine düzgün bir isim verilebilir. Şöyle yaparız
class Foo {
  var imageFile : File ? = ...
  fun deleteImage(){
      // 🧐 you can get away for now
      imageFile?.let { image ->
        if(image.exists()) image.delete()
      }
  }
}

26 Temmuz 2021 Pazartesi

Kotlin data Class

Giriş
Üye alanlar için getter(), setter(), equals(), hashCode() ve copy() metodları üretir. Açıklaması şöyle
1. data class cannot be abstract, inner, open or sealed.
2. At least 1 parameter is required in the primary constructor.
3. data class does not implement Serializable by default.
4. data class can implement interfaces and extend other classes (since v1.1).
Örnek
Şöyle yaparız
enum class RequestType {CREATE, DELETE}
data class RuleChange(val organizationId: String, val userIds: List<String>,
val request: RequestType)
Örnek
Açıklaması şöyle
If we want to exclude any property from being included in the automatically generated functions, we can put the property in the class body :

Only genre and artist properties will be used in the implementation of hashcode(), equal(), copy(), toString() method.
Şöyle yaparız
data class Song(val genre: String, val artist: String){
  var title: String;
}
val songA: Song = Song("Pop", "Jamie")
val songB: Song = Song("Pop", "Jamie")
songA.title = "Take the train"
songB.title = "All blues"
songA.equals(songB) // true
copy
Şöyle yaparız
val song: Song = Song("Jazz", "John")
val anotherSong: Song = song.copy()

print(song == anotherSong) // true
print(song === anotherSong) // false

val nextSong: Song = song.copy(artist = "Judy")

17 Temmuz 2021 Cumartesi

Kotlin open Anahtar Kelimesi

Giriş
Kotlin'de sınıflar final kabul edilir. Eğer kalıtmak istersek ata sınıfa open kelimesi eklenir.

Örnek
Arayüzlerde open anahtar kelimesine gerek yoktur. Zaten kalıtım olacağı bellidir. Şöyle yaparız.
interface Shape{
  fun side(): Int
  fun computeArea(): Double
  fun computePerimeter(): Double
  fun addColor(): String
}

class Rectangle(var l: Int, var w: Int): Shape(){
  override fun side(): Int {
    return 4
  }

  override fun computeArea(): Double {
    return (w*l).toDouble()
  }

  override fun computePerimeter(): Double {
    return (2*(l+w)).toDouble()
  }

  override fun addColor(): String {
    return "red"
  }
}
Örnek
Sınıflarda ise şöyle yaparız
open class Shape{
  //body

class Rectangle: Shape(){
  //body
}

14 Temmuz 2021 Çarşamba

Kotlin suspend Anahtar Kelimesi

Suspension Function
Açıklaması şöyle.
Suspending functions may suspend the execution of the current coroutine without blocking the current thread.
suspend vs Callback
Açıklaması  şöyle
Suspend functions are a direct replacement for callbacks — it is one of the basic premises behind structured concurrency. Callbacks make code hard to follow (ie. they make your code unstructured). The classic example of this is the pyramid of doom or callback hell. Coroutines (represented primarily as suspend functions in Kotlin) are designed to clean that kind of code up — callbacks are no longer required
suspend vs Flow
Açıklaması şöyle
When designing your methods and functions, start with a suspend function and if you get stuck, change it to a Flow.
 
Kotlin ve suspend Anahtar Kelimesi
Açıklaması şöyle.
You may find functions like kotlinx’s delay or Ktor’s HttpClient.post that need to wait for something or do intensive work before returning, and are marked with the suspend keyword.
Örnek
Şöyle yaparız
suspend fun delay(timeMillis: Long) {...}
suspend fun someNetworkCallReturningValue(): SomeType {
 ...
}
Suspend return Type
Açıklaması şöyle
The suspending world is nicely sequential
You have probably noticed that suspending functions don’t have special return types. They are really declared just like usual functions. We don’t need any wrapper like Java’s Future or JavaScript's Promise. This confirms that suspending functions are not asynchronous themselves (at least from the point of view of the caller), unlike JavaScript’s async functions, which return promises.

This is what makes asynchronous stuff easy to reason about in Kotlin. Inside a suspending function, calls to other suspending functions behave like normal function calls: we need to wait for the execution of the called function before getting the return value and executing the rest of the code.
Ancak google tarafından önerilen şey bir Result sınıfı tanımlamak. Böylece when ile kullanılabilir. Şöyle yaparız
sealed class Result<out R> {
  data class Success<out T>(val data: T) : Result<T>()
  data class Error(val exception: Exception) : Result<Nothing>()
}
when (result) {
  is Result.Success<LoginResponse> -> // Happy path
  else -> // Show error in UI
}

Coroutine builders
1. runBlocking metodu
Örnek
Şöyle yaparız
fun main() { 
  println("Hello,")
    
  // we create a coroutine running the provided suspending lambda
  // and block the main thread while waiting for the coroutine to finish its
//execution
  runBlocking {
    // now we are inside a coroutine
    delay(2000L) // suspends the current coroutine for 2 seconds
  }
    
  // will be executed after 2 seconds
  println("World!")
}
2. funCatching
Kendi Result sınıfını döner. Bizim artık Result sınıfı tanımlamamıza gerek kalmaz. Şöyle yaparız
val statusResult: Result<String> = runCatching {
  // function that may throw exception that needs to be handled
  repository.userStatusNetworkRequest(username)
}.onSuccess { status: String ->
  println("User status is: $status")
}.onFailure { error: Throwable ->
  println("Go network error: ${error.message}")
}
3. launch metodu - Fire and Forget
Örnek
Şöyle yaparız
fun main() { 
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L)
        println("World!")
    }
    println("Hello,") // main thread continues here immediately
    runBlocking {     // but this expression blocks the main thread
        delay(2000L)  // ... while we delay for 2 seconds to keep JVM alive
    } 
}
4. await metodu - Get Result
Örnek
Şöyle yaparız
fun main() {
    val deferredResult: Deferred<String> = GlobalScope.async {
        delay(1000L)
        "World!"
    }
    
    runBlocking {
        println("Hello, ${deferredResult.await()}")
    }
}