I want to write a function that takes an intersect...
# announcements
g
I want to write a function that takes an intersection type, but I don't know the syntax (or if it's possible in Kotlin). Here's what I'd imagine using a single ampersand like so:
Copy code
// Error here ---v
fun <T : Slugged & BaseModel> suggestSlug(
    tempSlug: String,
    clazz: Class<T>,
): String
I want to make sure the class passed to this function implements
Slugged
(to be sure it has a
.slug
property) and extends the abstract class
BaseModel
(to be sure it has an
.id
property and is a database
@Entity
class - I'm using Ebean). I found this, which shows the set-theory, but doesn't show the syntax I need (I apologize if I am misunderstanding any of this): https://kotlinlang.org/spec/type-system.html#intersection-types Should I just make an abstract
SluggedBaseModel
? I'd rather not because abstract vars annotated
@Column
need to be initialized and this should be a non-null required constructor parameter for each entity bean that uses it.
z
Kotlin doesn’t support expressing intersection types in code. It can handle intersection types that are inferred, but you can’t actually express such a type yourself unfortunately.
🤔 1
c
Copy code
fun <T> suggestSlug(
  tempSlug: String,
  clazz: Class<T>,
): String where T : Slugged, T : BaseModel
https://kotlinlang.org/docs/generics.html
😍 1
✔️ 1
👀 3
💯 1
It only works if you know the exact interfaces you want as parent though, you (very sadly) can't write
where T : S, T : Q
(but in your case it seems you know them so it should work fine)
g
Perfect. Thanks @CLOVIS! The most direct link I found is https://kotlinlang.org/docs/generics.html#upper-bounds A simple
|
or
&
would be prettier (especially if you could use it in a
typealias
), but at least the feature is in the language.
Of course, calling this function from Java now requires a cast to
(Class)
and a
@SuppressWarnings({"rawtypes", "unchecked"})
but I can live with that.
r
Denotable intersection and union types are on the team's radar, but it's not going to happen before the frontend re-write at a minimum (~ a year? no firm timeline). See https://youtrack.jetbrains.com/issue/KT-13108, it was mentioned in the 1.5 event too
c
I'm surprised it requires anything from the Java side, my understanding was that it's a direct equivalent of Java's
<T : A & B>
Sadly it's not powerful enough for what I want to do with it, hopefully the team with rework on that soon