Open kurtzace opened 3 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
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) {}
(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
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
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
lambda
or better use {println(it)}
or better is ::println
closure
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
to close with autoclosable
Meeting().use {
//use it....
}
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
mutableListOf to add - modify
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
lateinit - no need to do ?
safe call. But you need to init later.
@Nullable, @NotNull
org.jetbrains.annotations
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
sealed, extentions, data class, companion from youtube
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