0

So I'm trying to reduce this code and avoid the smart cast hint from IDE. The idea is I have a nullable variable of type T and I want to either map it to R or I just get R from a supplier in case the variable is null.

I've tried different approaches and came up with this one. Still it gives me the smart cast hint.

fun <T, R> T?.func(mapper: (T) -> R, supplier: () -> R): R =
    when(this) {
        null -> supplier()
        else -> mapper(this) // smart cast
    }

But I don't like the need for wrapping one of the lambdas in parenthesis. For example.

fun foo(value: String?): Int =
    value.func({ it.length + 20}) { 30 }

This may seem odd but the ideia in my context was to pass the variable as not nullable to a function that produced a R or call a function that generated a R.

fun bar(value: T?): R =
    when(value) {
        null -> func1()
        else -> func2(value) // smart cast
    }

Note: I've read this but its not the same.

hopeman
  • 2,778
  • 3
  • 18
  • 33
chriptus13
  • 705
  • 7
  • 20
  • 1
    what do you mean by `avoid smart cast`? for what purpose? – IR42 Jun 15 '20 at 02:21
  • 1
    The question isn't clear for me, are you asking in context of `smart cast` or the `wrapping of the lambda in parenthesis`? And btw you can always wrap both the lambda in the parenthesis for better readability than taking one outside. Taking trailing lambda outside is recommended when there is only 1 lambda in last parameter. – Animesh Sahu Jun 15 '20 at 02:27
  • 2
    If `mapper` was a method of `T`, then you could reduce the code as `(this?.mapper())?:supplier()`. – Venkatesh-Prasad Ranganath Jun 15 '20 at 02:37
  • Im asking in context to both is there any better way to do this avoiding the smart cast and make it better for readability? – chriptus13 Jun 15 '20 at 02:39
  • @Venkatesh-PrasadRanganath ya i taught about that and that solves both but the mapper isn't a method of `T` unfortunately. – chriptus13 Jun 15 '20 at 02:41
  • I re-read your question multiple times and it's still not clear what you're asking about. If you're bothered by having to wrap lambdas in parentheses, then you can declare a function and pass in a function reference instead of a lambda. If your question is about something else - please try providing more clarity. Also, avoid mixing multiple questions in one, prefer just posting multiple questions – Egor Jun 15 '20 at 02:57
  • What is the point in avoiding the smart cast? It’s not a warning. – Tenfour04 Jun 15 '20 at 05:12

1 Answers1

1

Following should avoid the smart cast hint

fun <T, R> T?.func(mapper: (T) -> R, supplier: () -> R): R {
    return this?.let { mapper(it) } ?: supplier()
}
sidgate
  • 14,650
  • 11
  • 68
  • 119