kurtzace / diary-2024

0 stars 0 forks source link

Kotlin notes #9

Open kurtzace opened 3 months ago

kurtzace commented 3 months ago

sealed, extentions, data class, companion from youtube image

function HOC, passed as param predicate: (String)->Boolean

{it.startsWith("K")}

hoc: list.forEach{ if(prediciate(it)) {.....} }

list.filterNotNull()

list.takeLast(2)

list.associate {it to it.length } // gives Map<String, Int>

orEmpty

kurtzace commented 2 months ago

Lambda passing

class Person (var name: String){
    fun displayWithLambda(func: (s:String) -> Unit) = func(name)
}
fun main(args: Array<String>) {
    var p = Person("Dariel")
    p.displayWithLambda(::printName)
}
fun printName(name: String){
        println(name)
}

when

        when (Answer){
            CorrectAnswer -> print("You were Correct")
            else -> print("Try again?")
        }

infix

// Infix function
// Operation overload
operator fun infix Header.plus(other: Header) : Header{
    return Header(this.name + other.name)
}
//for use as either
val h3 = h1 plus h2 or 
val h4 = h1 + h2

use open to enable extension

image

similarly open fun override fun

Interface

interface Logger {
    fun debug(message: String)
}

class StdoutLogger : Logger {
    override fun debug(message: String) {
    }}

to validate param

@JvmInline
value class Score(val score: Int) {
    init {
        if (score < 0 || score > 100) throw IllegalArgumentException("Score must be between 0 and 100") }}

class Exam {
    fun score(name: String, studentScore: Score) {}

data

(built in equals and hashcode and get and set)

data class Person(val name:String, val age:Int)

to get ref eq test use ===

intance.copy(age=32) //example copy with one diff param

can do DE structuring val (name, age) = instance

other ds

enums - all cases must be covered in when

has .name and .ordinal

custom parts in enum

enum class ErrorCodes(val error: Int) {
    None(0),
    Unknown(1),
    ConnectionLost(300)
}

enums have valueOf('String')

sealed classes like enum

image

outer and inner class to access outer data

class Outer {
    val name: String = ".."
    inner class Inner {
        fun doSomething() = println(name)
    }
}

also for annony inner class

object makes it singleton window.addListener( object: MouseAdapter() { override fun mouseClicked(e:

or object Logger {fun debug(msg:String)}{...} and use it like Logger.debug(...)

or like static method class Invoice{ companion object Logger{ fun debug( can be used like 'Invoice.debug'

fun supports default parameters

also extend existing classes

image

lambda

image

or better use {println(it)} or better is ::println

closure

image

Use apply when you need to modify properties and return the same object. Use with when you want to modify properties without requiring a dot operator for reference

image

to close with autoclosable

Meeting().use {
   //use it....
}

Collections

val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)

val fruits: List<String> = listOf("Apple", "Banana", "Orange")

predicates numbers.filter { it % 2 == 0 }

lazy exe - use sequences, see asSequence

image

mutableListOf to add - modify

null

nullable string val name:String? then name?. lowercase()

elvis for null coalesce

... = m?:Meeting()

safe case

val saveable = o as? ISavable

if we are sure it is not null m!!.close()

with let, call functions that dont expect null

image

lateinit - no need to do ? safe call. But you need to init later.

Java interop

@Nullable, @NotNull org.jetbrains.annotations

image
kurtzace commented 2 months ago

Cor routines

suspend fun compute(array: IntArray, start: Int, end: Int): Long coroutineScope { this CoroutineScope {

//println("Low: Slow, high: Shigh on ${Thread.current Thread())")

if (end start SEQUENTIAL THRESHOLD) {

(starts until end)

.asSequence()

.map { array[it]}

.sum().toLong() *coroutinescope

} else {

val mid int(start end) / 2

val left: Deferred <Long> async(Dispatchers.Default) { compute(array, start, mid)}

val right Deferred<Long> async(Dispatchers.Default) { compute(array, mid, end) }

left.await() right.await() coroutineScope