Created
April 15, 2019 20:52
-
-
Save xpepper/2d72a255a57ec3b4d231a2add2dab147 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReceiptText(private val template: String) : (Int) -> String { | |
override fun invoke(price: Int): String { | |
return template.replace("%%%", price.toString()) | |
} | |
} | |
val receiptText = ReceiptText("The total price to pay is %%% euro") | |
println(receiptText(10)) | |
fun receiptTxt(template: String): (Int) -> String { | |
return { price -> template.replace("%%%", price.toString()) } | |
} | |
val receiptTxt = receiptTxt("Devi pagarmi %%% soldi!") | |
receiptTxt(10) | |
object ReceiptTextObject { | |
operator fun invoke(price: Int): String { | |
return "price to pay is %%% euro".replace("%%%", price.toString()) | |
} | |
} | |
ReceiptTextObject(101) | |
sealed class TemplateString { | |
object ReceiptTextObj { | |
operator fun invoke(amount: Int): String = | |
receipt("My receipt for $%%%")(amount) | |
operator fun invoke(template: String, amount: Int): String = | |
receipt(template)(amount) | |
private fun receipt(template: String): (Int) -> String { | |
return { price -> template.replace("%%%", price.toString()) } | |
} | |
} | |
} | |
val receipt = TemplateString.ReceiptTextObj | |
receipt(10) | |
receipt("ciao, mi devi %%% gatti...", 123) | |
val functions = mutableListOf<(Int) -> String>() | |
functions.add(receiptTxt("TA %%%")) | |
functions.add(ReceiptText("Thank you for $%%%!")) | |
functions.add(TemplateString.ReceiptTextObj::invoke) | |
functions.mapIndexed { i, f -> f(10 + i) } | |
// --------------------------------- | |
// Functional Type | |
class Add(private val x: Int) : (Int) -> Int { | |
override fun invoke(y: Int): Int { | |
return x + y | |
} | |
} | |
// Functional value (anonymous inner class) | |
val add: (Int) -> (Int) -> Int = { x: Int -> { y: Int -> x + y } } | |
println(add::class) | |
val increment = add(1) | |
increment(3) | |
val increment2 = Add(1) | |
increment2(2) | |
val addTen = Add(10) | |
addTen(3) | |
fun words(string: String): List<String> { | |
return string.split(" ") | |
} | |
class Splitter : (String) -> List<String> { | |
override fun invoke(string: String): List<String> { | |
return string.split(" ") | |
} | |
} | |
val splitter: (String) -> List<String> = { s: String -> s.split(" ") } | |
splitter("ciao a tutti") | |
listOf("ciao a tutti", "domani è domenica").flatMap(splitter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment