Updated 29 November 2019
A domain-specific language (DSL) is a computer language specialized to a particular application domain. This is in contrast to a general-purpose language (GPL), which is broadly applicable across domains. Some examples of using DSLs (SQL, RegExp, Gradle).
What need we know to start DSL?
1.Lambda expressions
2.Higher-Order Function
3.Lambdas With Receivers
1.Lamda expression :
Lambda expression is a short way to define a function. A function without a name is called the anonymous function. Lambdas Expressions are anonymous functions that we can pass them as arguments to methods or return.
Lambda Expressions look like below:
2.Higher-Order Function
A higher-order function is a function that can take other functions as parameters and returns other functions.
Now Let’s start by converting a data model class into DSL
1 |
data class Employee(var name: String? = null, var id: Int=0, var dep: String? = null) |
Now let’s make the DSL higher-order function:
1 2 3 4 5 |
fun employee(block: (Employee) -> Unit): Employee { val emp = Employee() // Create the object block(emp) //Call the lambda which will use the Employee return emp } |
Finally, we have created our data model object in the DSL way.
1 2 3 4 5 |
val employee= employee { it.name="John" it.id=123 it.dep="mobikul" } |
It’s worked fine, but you need to use it
to access the properties instead of accessing them directly. We can fix it with the help of lambdas with receivers.
We will come back soon with part 2 lambdas with receivers
I hope this blog is useful to you. Thanks for reading.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.