Quantcast
Channel: starts with inside switch statement Kotlin - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by sirjoga for starts with inside switch statement Kotlin

$
0
0

This is really interesting question.

Maybe something like that, lol?

run {    operator fun String.unaryPlus() = "This is some message".startsWith(this)    when {+"This" -> { println("Starts with This") }+"That" -> { println("Starts with That") }        else -> { println("Doesn't start with This or That") }    }}

run is for operator overload localization

Of course you can use function or extension function instead of operator.

fun String.a() = "This is some message".startsWith(this)when {"This".a() -> { println("Starts with This") }"That".a() -> { println("Starts with That") }    else -> { println("Doesn't start with This or That") }}

PS. And of course you can write all this as library code ))

class PredicateContext<T>(private val predicate: (T) -> Boolean) {    operator fun T.invoke() = predicate(this)}

... and use it anywhere

PredicateContext<String> { "This is some message".startsWith(it) }.run{    when {"This"() -> println("Starts with This")"That"() -> println("Starts with That")        else -> println("Doesn't start with This or That")    }}

Viewing all articles
Browse latest Browse all 5

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>