context provides ability to continue a conversation EXTREMELY IMPORTANT: CONTEXT When you have context, you need fewer words and you can be expressive. 14 One of the key things about DSL is they carry the context with them..
to it. The last time I checked we live in a free country right! So absolutely we can add methods to any java class we want. (As long as we can access the class) EXTENSIONS WORK ON JAVA CLASSES TOO 23
println("Driving $distance") } } infix fun Car.accelerate(speed:Int){ println("accelerate $speed") } val car = Car() // infix function call car accelerate 20 accelerate 20
the code, more it is pleasant to read. When a lambda is a last parameter, it gets a special treatment. It can step outside of the function parentheses. NO BRACKETS FOR PASSING THE LAST LAMDA 25
function that takes Int as an argument and returns Unit */ fun process(num: Int, func: (Int)->Unit){ func(num * 2) } // the last lambda can be written outside the parentheses process(2) { num-> println(num) } 4
type of lambdas execute, they are going to run in the context of the context object. Think of a normal lambda as an arbitrary function. Running lambda in the context of an object makes it execute like it is a method of that class of that context object. WHAT ARE IMPLICIT RECEIVERS ? 29
structure. They could be classes, functions implicit lambda receiver. Their sole purpose is to help create a DSL syntax and build them on a particular class. WHAT’S A TYPE-SAFE BUILDER? 38
Name() var id = "" var gender = "" var age = 0 var contact = Contact() fun name(func:Name.()->Unit){ name = Name().apply{ func() } } fun contact(func:Contact.()->Unit){ contact = Contact().apply{ func() } } }
that too many functions can be called in the context. We can call methods of every available implicit receiver inside a lambda and therefore get an inconsistent result.” THE SCOPE PROBLEM 44 What does Kotlin docs say?