Issue
I have a generic type (T: Any?
) that I need constrained in one situation never to be null
:
class Repository<T> { // T may be a non-null or nullable type.
fun getFromFoo(): T {}
fun getFromBar(): T {} // This is never null. Can I mark it as so?
}
val repository = Repository<String>()
val fromFoo: String = repository.getFromFoo() // Returns a non-null String.
val fromBar: String = repository.getFromBar() // How do I make this work?
val repository = Repository<String?>()
val fromFoo: String? = repository.getFromFoo() // Returns a nullable String.
val fromBar: String = repository.getFromBar() // How do I make this return a non-null String?
While I would ideally refactor these into separate types (like FooRepository
and BarRepository
), is there any way to get this type constraint functionality?
Solution
What you need is the type T & Any
— an intersection of generic T
and Any
. It represents such subtype of T
that can never contain nulls.
Unfortunately the intersection types and this intersection in particular currently are non-denotable in Kotlin, meaning that you can't declare a return type of a function to be non-nullable subtype of T
.
Answered By - Ilya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.