Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin lambda with explicit return type

Tags:

lambda

kotlin

I have the following Kotlin classes:

sealed class Result {
  data class Success()
  data class Failure()
}

class Single<R>(val value: R?, throwable: Throwable?) {
  fun map(mapper: (R) -> T): Single<T> {
    return Single(mapper(value!!), null)
  }
  fun onError(recover: (Throwable) -> T): Single<T> {
    return Single(recover(throwable!!))
  }
}

And I have the following function:

fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() }
    .onError { Single.Error() }
}

But onError fails with:

Type Mismatch.
  Required: Single.Success
  Found:    Single.Error

I realize I can work around this with:

fun handle(single: Single<String>): Single<Result> {
  return single
    .map { Single.Success() as Single<Result> }
    .onError { Single.Error() as Single<Result> }
}

But I prefer to force type inference to work left-to-right as much as possible. That is, I'd prefer the { Single.Success() } lambda to specify and explicit return type.

Is an explicit return type allowed in Kotlin? the functionLiteral Grammar makes it look like it can't, but I'm not an expert in reading grammars.

like image 700
Heath Borders Avatar asked Nov 16 '18 22:11

Heath Borders


2 Answers

You actually cannot explicitly declare the return type in a Kotlin lambda:

One thing missing from the lambda expression syntax presented above is the ability to specify the return type of the function.

https://kotlinlang.org/docs/reference/lambdas.html#anonymous-functions

like image 130
gutenmorgenuhu Avatar answered Sep 28 '22 16:09

gutenmorgenuhu


This worked! Someone else gave me the answer in another forum, and if they respond here, I'll mark their answer correct.

fun handle(single: Single<String>): Single<Result> {
  return single
    .map<Result> { Single.Success() }
    .onError<Result> { Single.Error() }
}
like image 24
Heath Borders Avatar answered Sep 28 '22 17:09

Heath Borders