Search code examples
unit-testingkotlinsealed-class

Kotlin sealed class and type inference


im using a sealed class to report back success or error to client code:

sealed class Result<out T : Any> {
    data class Success<out T : Any>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

But im stuck getting even the simplest unit test to compile using it:

    val error = Result.Error(IOException("message"))
    assertThat(error, instanceOf(Result.Error::class.java))

I get the message : Type Inference failed. Not enough information to infer parameter T in fun instanceOf(type : Class<*>) : Matcher!

Looks like im missing something important in Kotlin.

Thanks for helping me out!


Solution

  • there is no problem with your code for me.

    import org.hamcrest.CoreMatchers.instanceOf
    import org.junit.Test
    
    import org.junit.Assert.*
    import java.io.IOException
    
    class ExampleUnitTest {
        @Test
        fun test1() {
            val error = Result.Error(IOException("message"))
            assertTrue(error is Result.Error)
        }
    
        @Test
        fun test2() {
            val error = Result.Error(IOException("message"))
            assertThat(error , instanceOf(Result.Error::class.java))
        }
    
        sealed class Result<out T : Any> {
            data class Success<out T : Any>(val data: T) : Result<T>()
            data class Error(val exception: Exception) : Result<Nothing>()
        }
    }
    

    Also, I'll suggest you to use the keyword is to check if your class is an instance of something in kotlin (like in test1)