You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中如何约束泛型?限定PublishSubject接收可食用水果

Solution: Use Kotlin's Intersection Types for Constrained RxJava Stream

Great question! Let's break this down and find a clean, type-safe solution without subclassing PublishSubject.

First, your initial attempt PublishSubject<Fruit : Edible> uses invalid Kotlin syntax for generic constraints. What you need is a way to enforce that the stream only accepts types that are both Fruit and Edible. Kotlin supports this with intersection types, denoted by the & operator.

Correct Implementation

Here's how to create your stream with the exact constraint you want:

// Create a PublishSubject that only accepts types which are Fruit AND Edible
val stream = PublishSubject.create<Fruit & Edible>()

This works because:

  • The Fruit & Edible intersection type tells the compiler that only objects implementing both Fruit (or its subclasses) and Edible are allowed in the stream.
  • Your Apple class (which extends Fruit and implements Edible) will be accepted without issue.
  • Non-Fruit Edible types (like IceCream or Potato) will be rejected at compile time, as will Fruit subclasses that don't implement Edible.

Simplify with a Type Alias

If you need to reuse this constrained type across multiple places, define a type alias to keep code clean:

// Define a reusable alias for types that are both Fruit and Edible
typealias EdibleFruit = Fruit & Edible

val stream = PublishSubject.create<EdibleFruit>()

Why Avoid the Filter Approach?

Your initial idea of PublishSubject<Edible>.create().filter { it is Fruit } is not ideal because:

  • It relies on runtime checks instead of compile-time type safety. Invalid objects can still be sent to the stream (they'll just be filtered out later), which hides potential bugs.
  • It's less efficient, as it requires processing every Edible object even if it's not a Fruit.

Key Takeaway

Using Kotlin's intersection types gives you compile-time enforcement of your dual constraint, no subclassing required. This is the most idiomatic and safe way to achieve your goal with RxJava in Kotlin.

内容的提问来源于stack exchange,提问作者Arturs Vancans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:27:25