KingSpnk
KingSpnk

Reputation: 13

Expected type does not accept nulls in Java, but the value may be null in Kotlin

I am building a sports app and ran into a problem during compilation. The submission variable inside the getCachedSubmission function is null and seems to require a null handle, but I'm not sure. This is the code below:

import com.bluebeam.premierleaguego.features.model.SubmissionWrapper
import com.bluebeam.premierleaguego.data.reddit.RedditAuthentication
import com.bluebeam.premierleaguego.data.service.RedditService
import com.google.common.base.Optional
import io.reactivex.Single
import net.dean.jraw.models.CommentSort
import net.dean.jraw.models.Submission
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import javax.annotation.Nullable

/**
 * Implementation of the [SubmissionRepository] interface. Stores [SubmissionWrapper]s in a map
 * keyed by their id.
 * TODO: should there be a limit to how many submissions are cached?
 */
@Singleton
class SubmissionRepositoryImpl
@Inject constructor(
    val redditAuthentication: RedditAuthentication,
    val redditService: RedditService) : SubmissionRepository {
  private val idToSubmissionMap = HashMap<String, SubmissionWrapper>()

  override fun getSubmission(
      id: String,
      sort: CommentSort,
      forceReload: Boolean): Single<SubmissionWrapper> {
    // Use submission in cache if available and has the right comment sorting.
    if (!forceReload && idToSubmissionMap[id] != null && idToSubmissionMap[id]?.sort == sort) {
      return Single.just(idToSubmissionMap[id])
    }
    return redditService.getSubmission(redditAuthentication.redditClient, id, sort)
        .flatMap { s: Submission ->
          val wrapper = SubmissionWrapper(s)
          wrapper.sort = sort
          idToSubmissionMap[wrapper.id] = wrapper
          Single.just(wrapper)
        }
  }


  override fun getCachedSubmission(id: String): Optional<Submission> {
    val submission = idToSubmissionMap[id]?.submission
    return Optional.of(submission)
  }


  override fun saveSubmission(submissionWrapper: SubmissionWrapper) {
    idToSubmissionMap[submissionWrapper.id] = submissionWrapper
  }

  override fun reset() = idToSubmissionMap.clear()
}

The error that I continue to get from the getCachedSubmission function is: Expected type does not accept nulls in Java, but the value may be null in Kotlin. If there are any suggestions on how to resolve this that would be helpful. Thanks!

Upvotes: 1

Views: 1591

Answers (2)

Jamin
Jamin

Reputation: 1402

Use ? next to the variable datatype to allow it to accept a null value. Have an if statement within the getCachedSubmission function (which also has ?) to control the flow of information if the variable is null.

In this example, I create a argument variable of type String? to allow it to later be changed to null. In the try/catch block (which I put as extra layer of exception handling just in case) I pass an argument to getCachedSubmission, and within the function the information is handled to change what is displayed if the argument passed is null.

To see what happens when the argument passed is null uncomment the argument = null; line of code.

var argument: String? = "abc"; 
fun main(args: Array<String>) {
    try
    {
        //uncomment me below
        //argument = null;
        argument = getCachedSubmission(argument);
        println(argument);
    }
    catch(e: Exception)
    {
        //Some sort of exception encountered
        println("do nothing");
    }

}
fun getCachedSubmission(parameter: String?): String
{
    var flow = "normal";
    println(parameter);
    if(parameter == null)
    {
        flow = "not normal"
        return flow;
    }

    return flow;
}

Hope this helps.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170899

Optional.of doesn't accept null (it'll throw an exception if it gets one), but use of ?. means submission can be null. Use Optional.ofNullable instead.

Upvotes: 2

Related Questions