is there a manner to use a type variable ("generic...
# getting-started
a
is there a manner to use a type variable ("generic", in this case
W
in the example below) with more than one constraint, if a class delegates some of its implementation details? e.g.
Copy code
class DirectedEdgeWeighted<W> private constructor (val de: DirectedEdge, val w: W, val wAccretion: (W, W) -> W): DirEd by de where W: Any, W: Comparable<W> { ... }
produces syntax errors, even after trying several permutations in how the part after the constructor is declared, and before the beginning (say,
data class
) too. It is important that
DirectedEdgeWeighted
is-a
DirEd
but not is-a
DirectedEdge
so inheritance is not a solution.
This issue is interesting on the basis of syntax principles, so please let's ignore the possibility of making inheritance feasible. I could hypothetically drop
W: Any
as a workaround, yes, but a workaround is not the goal of the answer that I seek. Reassuming, without the example above: my question is: is there a manner to use a type variable ("generic") with more than one constraint, if a class delegates some of its implementation details? Thanks for your kind and analytical interest 🙂
y
It seems like putting the
where
on a separate line just works:
Copy code
interface DirEd
class DirectedEdge: DirEd
class DirectedEdgeWeighted<W> 
    constructor (val de: DirectedEdge, val w: W, val wAccretion: (W, W) -> W): DirEd by de 
where W: Any, W: Comparable<W> { }

fun main(){
    println(DirectedEdgeWeighted(DirectedEdge(), 20, Int::plus))
}
a
Youssef: awesome, thanks. That works 🙂, and I really appreciate your reply. There is a manner! On a different note, since a LF/CR is whitespace, do you know if this could be a minor kink in the front end, or is this for some reason deliberate? If not, where would be the right place to ask? Cheers!
y
Asking in #compiler will probably give you the best results. It seems to me that this might just be a kink in the compiler. The kotlin grammar for class definitions doesn't seem to suggest that such whitespace is required at all.
a
👆👌👍