Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Type casting to satisfy multiple type constraints

Is it possible to typecast to satisfy multiple type constraints in kotlin?

Say I have the following case, but want to avoid type casting to class C (in case multiple classes implement A and B, or I don't know type C):

interface A
interface B

class C: A, B

fun <T> foo(bar: T) where T: A, T: B {

}

Is it possible to typecast to A and B simultaneously? Smart cast doesn't seem to allow this. Can I manually cast somehow?

val c = C()
foo(c) // works

val d: Any = c
if (d is A && d is B) {
    foo(d) // smart cast doesn't work here, compiler error
}

// Something like this maybe?
foo(d as A && B)

I know it's possible by creating a new interface that inherits from both A and B, and then use that, but that may not be possible if I don't control the classes in question.

Thanks

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The type has to explicitly implement the required interfaces and since Any cannot be both B and A (even though it implements both) simultaneously there has to be a third type, like C.

This similar question has a generic work around; Is intersection casting possible in Kotlin?

so arbitrary types T which implement A and B can be recognized as such but is and as can't be directly composed with && which makes it impossible to satisfy your functions type constraints without some kind of explicitly implementing wrapper.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!