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

Mikael Alfredsson

12/12/2020, 10:57 AM
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

Animesh Sahu

12/12/2020, 12:29 PM
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

Mikael Alfredsson

12/12/2020, 12:36 PM
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

Animesh Sahu

12/12/2020, 12:38 PM
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

Mikael Alfredsson

12/12/2020, 12:40 PM
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

Animesh Sahu

12/12/2020, 12:40 PM
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

Mikael Alfredsson

12/12/2020, 12:42 PM
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

Animesh Sahu

12/12/2020, 12:44 PM
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

Mikael Alfredsson

12/12/2020, 12:45 PM
Yes, I can probably find some nice workarounds, I was just curious if it was possible to do something like
listOf<Interf & Interf2>(…)
a

Animesh Sahu

12/12/2020, 12:45 PM
Currently, no. Check #language-proposals to discuss with devs.
m

Mikael Alfredsson

12/12/2020, 12:46 PM
👍 Thanks for the input
2 Views