I know that kotlin accepts the following syntax ``...
# announcements
m
I know that kotlin accepts the following syntax
Copy code
fun <T> f(): Foo where T : Bar, T : Baz { ... }
but can I do the same with for example a map?
val map = mapOf<String, T (where T:bar,  T:Baz)>
a
Yes, this does work:
Copy code
interface Interf
interface Interf2

class A : Interf, Interf2
class B : Interf, Interf2

fun main() {
    val list = listOf(
        A(),
        B()
    )

    test(list)
}

fun <T> test(list: List<T>) where T : Interf, T : Interf2 {

}
It has intersectional type
Here's another reference if you like to check it out: https://stackoverflow.com/q/62241262/11377112
m
So the check will be in the receiving function, not in the “listof”?
Copy code
interface Interf
interface Interf2
interface Interf3

class A : Interf, Interf2
class B : Interf, Interf3
fun main() {
    val list = listOf(
        A(),
        B() // here I want this to fail.
    )
   list.forEach{
     val a = it as Interf
     val b = it as interf2 // this will be a runtime exception
   }
}
a
You cannot intersectional specify the types actually, if you can define a use case I can better help?
The functions can bound these to get correct types, but I don't see any need in this situation (local scopes)
m
in my case above, i don’t really have a function and in my real life code, the list is a global list that is being used inside another function, but its not part of the functions parameters (since its a web server route function)
🤔 1
a
And basically if you have all the types in your module (doesn't depend on other) you can always make a new interface combining both, and class which inherit it.
m
I mean, i can live without it, but it would be nice to have compile time checks instead of runtime 🙂
with
listOf<Interf2>(A(), B())
the compiler would complain in my example, but I can only do that check for one interface.
a
In my case above, i don’t really have a function and in my real life code, the list is a global list that is being used inside another function, but its not part of the functions parameters (since its a web server route function)
Best bet would be to define the list as
List<Any>
and provide the add/remove methods yourself and add constraints there.
That's basically how arrays are handled in the backside inside the list tbh...
m
Yes, I can probably find some nice workarounds, I was just curious if it was possible to do something like
listOf<Interf & Interf2>(…)
a
Currently, no. Check #language-proposals to discuss with devs.
m
👍 Thanks for the input