Skip to content

Instantly share code, notes, and snippets.

@Zhuinden
Created October 14, 2017 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zhuinden/854b85d3444455430e4744e9d5d20e9a to your computer and use it in GitHub Desktop.
Save Zhuinden/854b85d3444455430e4744e9d5d20e9a to your computer and use it in GitHub Desktop.
Tinkering with Kotlin's infix
class ResultRobot {
fun isSuccess() : Boolean = true;
infix fun validate(function: ResultRobot.() -> Unit) : ResultRobot {
return apply {
function.invoke(this)
};
}
}
class PaymentRobot(var amount: Int = 0, var email: String? = null) {
fun send() : ResultRobot {
return ResultRobot();
}
infix fun with(function: PaymentRobot.() -> Unit): PaymentRobot {
return this.apply(function);
}
infix fun <T> execute(function: PaymentRobot.() -> T): T {
return function.invoke(this);
}
companion object {
infix fun payment(function: PaymentRobot.() -> Unit) : PaymentRobot {
return PaymentRobot().with(function);
}
}
}
fun blah() {
payment {
amount = 5;
email = "blah@blah.com";
} execute {
send()
} validate {
isSuccess()
}
}
class ResultRobot {
fun isSuccess(): Boolean = true;
infix fun validate(function: ResultRobot.() -> Unit): ResultRobot = apply {
function.invoke(this)
};
}
class PaymentRobot(var amount: Int = 0, var email: String? = null) {
fun send(): ResultRobot {
return ResultRobot();
}
infix fun <T> execute(function: PaymentRobot.() -> T): T = function.invoke(this);
}
private fun payment(function: PaymentRobot.() -> Unit): PaymentRobot = PaymentRobot().apply { function(this) }
fun blah() {
payment {
amount = 5;
email = "blah@blah.com";
} execute {
send()
} validate {
isSuccess()
}
}
class ResultRobot {
fun isSuccess() : Boolean = true;
infix fun validate(function: ResultRobot.() -> Unit) : ResultRobot {
return apply {
function.invoke(this)
};
}
}
class PaymentRobot(var amount: Int = 0, var email: String? = null) {
fun send() : ResultRobot {
return ResultRobot();
}
infix fun with(function: PaymentRobot.() -> Unit): PaymentRobot {
return this.apply(function);
}
infix fun <T> execute(function: PaymentRobot.() -> T): T {
return function.invoke(this);
}
}
private fun payment() : PaymentRobot = PaymentRobot()
fun blah() {
payment() with {
amount = 5;
email = "blah@blah.com";
} execute {
send()
} validate {
isSuccess()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment