Hey guys, is there a way to tell the compiler to n...
# announcements
m
Hey guys, is there a way to tell the compiler to not accept generic types as reified type argument?
Copy code
inline fun <reified Value : Any> test1(): Value = TODO()
inline fun <reified Value : Any> test2(): List<Value> = TODO()

val test: List<Int> = test1()
In the example using
test1()
(accidentally instead of
test2()
) should raise an error because I cannot get the generic type of the
List
anyway.
r
But, reified types are generic
m
I believe that this would require higher kinded types, which Kotlin doesn’t support
r
In your example your applied generic is
List<Int>
not
List
in higher kind position.
m
@raulraja I guess that doesn’t allow me to make
test1()
behave differently for
List<…>
, does it?
@Ruckus i.e.
Value = Int
-
Int
isn’t generic, is it? Or am I using the wrong term somewhere?
m
In a type system without higher kinded types, there is no way to specify for a generic parameter that it is a base type (i.e kind
*
), or a generic type (i.e kind
* -> *
). You have to take all of them (both kinds
*
and
* -> *
)
r
Okay, I think I now see what you mean. (I meant that
Value
in your example is a generic type, which is required by
reified
). If you're saying you don't want
Value
to resolve to a type which in turn has a generic type, no it's not possible as far as I am aware. If you're saying you want different behavior if there is a generic parameter, you can use reflection.
m
Okay, thanks you guys. 👍 Will work around it for now by using clear distinct names and hope that people won’t use the wrong one.
r
I'm not sure what you are trying to achieve but it's easy to see what the result would be if you type your function:
Copy code
test1<List<Int>>() // Value is `List<Int>`
test2<Int>() // List<Int>
But yeah, you can't use a kind in that position. because of no HKTs. yet... https://github.com/Kotlin/KEEP/pull/87 😉
If that makes it to the lang you'd be able to use kinds in that position...
Copy code
fun <F<_>, A, B> transform(fa: F<A>, f: (A) -> B): F<B> given Functor<F> = F.map(fa, f)
The you can use your polymorphic function to satisfy all types for a which a Functor instance exists:
Copy code
transform(listOf(1), { it + 1 })
transform(Option(1), { it + 1 })
transform(Try(1), { it + 1 })
m
looks complicated 😮 but thanks!
d
There is an annotation called
PureReifiable
to denote that a particular reified type parameter can be a generic type: https://github.com/JetBrains/kotlin/blob/master/core/builtins/src/kotlin/internal/InternalAnnotations.kt#L25 but it is
internal
😕
😯 1
r
@damian do you know of any examples that use
@PureReifiable
?
d
@raulraja Looks like it's only used for things like
arrayOf
,
emptyArray
,
arrayOfNulls
👍 1