Construct object through parent sealed class, and child private constructor

Construct object through parent sealed class, and child private constructor

Hi,

I want to implement some Scala inspired

Try

monad

I wanted to know if it is possible to make child class (

Success

and

Failure

) not instantiate by themselves (no public constructor), but only from the

Try.Companion.invoke

method. Here’s my current code with public constructor for both child, when I make them private I got an error in

invoke

method (which I understand). I found nothing in the Kotlin documentation about this kind of thing and I don’t think it is possible, so I post here just in case


sealed class Try<T> { companion object { operator fun <T>invoke(elem: () -> T) = try { Success(elem()) } catch (e: Exception) { Failure<T>(e) } } } data class Success<T>(val value: T) : Try<T>() data class Failure<T>(val e: Exception) : Try<T>()

Thanks in advance 😀

submitted by /u/lepaincestbon
[link] [comments]