https://kotlinlang.org logo
#announcements
Title
# announcements
l

LeoColman

11/07/2019, 3:35 PM
But I don't really want to, I want it to cast everything to Any if the user doesn't provide the value
r

Ruckus

11/07/2019, 3:40 PM
I don't know anything about your use case, but that sounds like a terrible user experience to me in the Kotlin world.
l

LeoColman

11/07/2019, 3:40 PM
It's for a DSL
Not exactly to be seen, just to be used
c

Casey Brooks

11/07/2019, 3:42 PM
How does the DSL use that type param? If it matches a function arg, then maybe setting its default value to
Any()
is what you want?
l

LeoColman

11/07/2019, 3:44 PM
The DSL uses the type param to return a
Sequence<T>
. Inside the DSL, the values of
T
may share a common type
Y
. I want to return
Sequence<Y>
if they do, and
Sequence<Any>
if they don't
It's for something like:
Copy code
class Y
class A : Y
class B : Y

buildSequence<Y> {
      creatingValue<A> { A() }
      creatingValue<B> { B() }
}
The compiler can't infer the type this way, and I didn't want the user to be forced to write
buildSequence<Y>
, just
buildSequence { }
which would return
Sequence<Y>
And perhaps for the user
Sequence<Any>
is enough
c

Casey Brooks

11/07/2019, 3:47 PM
Messing around type projections or bounds might be what you’re after, though I’m not familiar enough with them to know if they will fit this use-case https://kotlinlang.org/docs/reference/generics.html#variance
l

LeoColman

11/07/2019, 3:47 PM
I tried to mess with many of them 😕
Perhaps I"m overthinking this, and there's no problem in typing
buildSequence<Any>
if the user wants it
s

streetsofboston

11/07/2019, 4:09 PM
Try to use this annotation. It may help.
@BuilderInference
E.g. there is this code building a `Flow<T>`:
Copy code
public fun <T> flow(@BuilderInference block: suspend FlowCollector<T>.() -> Unit): Flow<T> = SafeFlow(block)
Just by calling
emit(instancOfMyType)
in the provided lambda (argument to
block
), the compiler can infer that
T
is
MyType
👏 1
l

LeoColman

11/07/2019, 4:14 PM
That seems interesting!
Let me try
l

LeoColman

11/07/2019, 4:16 PM
And the example is practically my use case
👍 1
How can I use the
@Experimental
without requiring the compiler flag for the client to use?
s

streetsofboston

11/07/2019, 4:32 PM
I think you’d have to mark this part of your API as experimental as well, since it promises something to the user of your API that only this experimental feature can offer.
l

LeoColman

11/07/2019, 5:09 PM
Unfortunately it didn't work. still getting the "Not enough information to infer parameter"
Any tips, @streetsofboston?
It works if I enable the new type inference
I think that's the point, right? xD
👌 2
3 Views