How to reference parameterized constructor in Kotlin?

101 views Asked by At

So I have this definition:

    sealed interface ParseResult<out R> {
        data class Success<R>(val value: R) : ParseResult<R>
        data class Failure(val original: String, val error: Throwable) : ParseResult<Nothing>
    }

I want to wrap certain elements in a Success. And I know I can do it like this...

    list.map{ParseResult.Success(it)}

But is there a way to use a constructor reference?

   list.map(ParseResult::Success) //this won't compile
1

There are 1 answers

0
Sweeper On

You can use a constructor reference if you add an import:

import somepackage.ParseResult.Success

Or even a typealias:

typealias Success<R> = ParseResult.Success<R>

Then you can do:

list.map(::Success)

The idea here is to make ParseResult.Success referrable by a simple name.

Not being able to do ParseResult::Success does look like a bug to me though. Compare:

class Outer {
    class Nested
}
class OuterGeneric<T> {
    class Nested
}

fun main() {
    val x = Outer::Nested // works
    val y = OuterGeneric::Nested // error
}