https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Asq

04/02/2022, 2:28 PM
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

Youssef Shoaib [MOD]

04/03/2022, 11:25 AM
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

Asq

04/04/2022, 6:45 PM
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

Youssef Shoaib [MOD]

04/07/2022, 7:47 AM
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

Asq

04/09/2022, 1:09 PM
👆👌👍
2 Views