I've read the docs on it 3 times and I still have no idea what it does. Can someone ELI5 (Explain Like I'm Five) it please? Here's how I'm using it:
fun main(args: Array<String>) { val UserModel = UserModel() val app = Javalin.create().port(7000).start() with (app) { get("/users") { context -> context.json(UserModel) } } }
Kotlin with. Like apply , with is used to change instance properties without the need to call dot operator over the reference every time. data class Person(var name: String, var tutorial : String) var person = Person("Anupam", "Kotlin") with(person) { name = "No Name" tutorial = "Kotlin tutorials" }
In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true , and otherwise evaluates and returns its second operand.
Kotlin :: apply In Kotlin, apply is an extension function on a particular type and sets its scope to object on which apply is invoked. Apply runs on the object reference into the expression and also returns the object reference on completion.
Kotlin double colon operator The double colon operator (::) is used to create a class or a function reference.
with
is used to access an object's members and methods without having to refer to the object once per access. It is (mostly) for abbreviating your code. It is frequently used when constructing an object:
// Verbose way, 204 characters: var thing = Thingummy() thing.component1 = something() thing.component2 = somethingElse() thing.component3 = constantValue thing.component4 = foo() thing.component5 = bar() parent.children.add(thing) thing.refcount = 1 // Terse way, 182 characters: var thing = Thingummy() with(thing) { component1 = something() component2 = somethingElse() component3 = constantValue component4 = foo() component5 = bar() parent.children.add(this) refcount = 1 }
The documentation says:
inline fun <T, R> with(receiver: T, block: T.() -> R): R (source)
Calls the specified function block with the given receiver as its receiver and returns its result.
The way I think of it is that it is calling a function (the block
) where this
in the scope of the block
is the receiver
. Whatever the block
returns is the return type.
Essentially calling a method where you provide the implicit this
and can return any result from it.
Here is an example to demonstrate:
val rec = "hello" val returnedValue: Int = with(rec) { println("$this is ${length}") lastIndexOf("l") }
The rec
in this case is the receiver of the function call - the this
in the scope of the block
. The $length
and lastIndexOf
are both called on the receiver.
The return value can be seen to be an Int
because that is the last method call in the body
- that is the generic type parameter R
of the signature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With