0

Acording to intellij and gradle, this variable a type is Deferred<{Comparable & java.io.Serializable}>:

val a = async(IO) { possibleIdDeferred.await()?.also { repo.findAttrById(it) } ?: run { "" } }

where possibleIdDeferred is Deferred<Long?> and this is the repo function:

@Cacheable("someCacheName")
suspend fun findAttrById(id: Long) = entityRepo.findById(id)!!.someAttr

where entityRepo declaration is

@Repository
interface EntityRepo : CoroutineCrudRepository<Entity, Long> {
    suspend fun findByAttr(attr: String): Entity?
}

If I add as String as here:

val a = async(IO) { possibleIdDeferred.await()?.also { repo.findAttrById(it) as String} ?: run { "" as String} }

I get [USELESS_CAST] No cast needed. If I try a.await() as String I get [CAST_NEVER_SUCCEEDS] This cast can never succeed. What should I change to make variable a type String?

rado
  • 5,720
  • 5
  • 29
  • 51
  • 1
    If the `async` call above is supposed to return `repo.findAttrById(it)` as a result, then you're using wrong scoping function - replace `also` with `let` (see: https://kotlinlang.org/docs/reference/scope-functions.html#function-selection) – Guest 21 Jan 09 '21 at 23:30
  • @Guest21 damn, you're right. With `also ?: run` I was returning `Long? :? String`. What I really wanted was `let`. Thanks for noticing what I wanted instead of what I asked. If you wish, please fill up an answer for me to accept it. If you don't, I intend to edit this question to point out the different return types my confusion was about :) – rado Jan 09 '21 at 23:41

1 Answers1

0

Since also returns its own context, I had

val a = someNullableInt ?: emptyString

leading to this strange type on question title. I fixed it changing also to let, since what I really wanted returned was the last statement

rado
  • 5,720
  • 5
  • 29
  • 51