#Scope Functions in Kotlin
this Context | it Context | |
---|---|---|
Produces last expression | with,run | let |
Produces receiver | apply | also |
fun add(a:Int,b:Int):Int= a+b | |
fun hof(a:Int,b:Int,func:(Int,Int)->Int)=func(a,b) | |
fun main() { | |
val result1:Int=hof(3,4,::add) | |
println("result1=$result1") | |
val result:Int=hof(1,2,func={a:Int,b:Int->a+b}) | |
//val result:Int=hof(1,2){a:Int,b:Int->a+b} | |
println("result=$result") |
package localfunctions | |
fun first(): (Int) -> Int { | |
val func = fun(i: Int) = i + 1 | |
return func | |
} | |
fun second(): (String) -> String { | |
val func2 = { s: String -> "$s!" } | |
return func2 |
package main | |
class Constructors(val color:String){ | |
init { | |
println("Init Color=$color") | |
} | |
//val or var is not allowed on secondary constructors | |
//You cannot declare a return type for a secondary constructor | |
constructor(color:String,value:Int):this(color){ | |
println("Color=$color,Value=$value") |
#Scope Functions in Kotlin
this Context | it Context | |
---|---|---|
Produces last expression | with,run | let |
Produces receiver | apply | also |
package main | |
open class Pet | |
class Dog:Pet() | |
inline fun <reified T>check(t:Any)=t is T | |
fun main(){ | |
var isValid:Boolean=check<Pet>(Dog()) | |
println(isValid) |
package main | |
data class Num(var value:Int) | |
infix fun Num.plus(num:Int)=value + num | |
operator fun Num.plus(num:Num)=value+num.value | |
fun main(){ | |
var result=Num(4) plus 3 |
package main | |
//Covarient example start | |
interface Source<out T> { | |
fun nextT(): T | |
} | |
class Complement<Int>(var num:Int):Source<Int>{ | |
override fun nextT()=num | |
override fun toString()="${this::class.simpleName}" | |
} |
package main | |
abstract class AB | |
interface INTF | |
open class X | |
data class Y:X() | |
sealed class Z | |
class A{ | |
class B | |
inner class C | |
object D{//can implement interfaces |
// PropertyDelegation/FileDelegate.kt | |
package propertydelegation | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
import checkinstructions.DataFile | |
class FileDelegate : | |
ReadWriteProperty<Any?, String> { | |
override fun getValue( |
//Zipping | |
//Flattening | |
//Sequences (Lazy mapping) |