Java中的联合类型 [英] Union types in Java
问题描述
我已经使用C#一段时间了,并试图使自己对Java更加熟悉.因此,我试图迁移我每天在C#中使用的一些基本模式,甚至只是为了了解JVM和dotnet之间的差距并弄清楚如何处理它们.这是我遇到的第一个问题-选项类型-somethiong,在许多语言(例如Koltlin)中都很容易实现
I've been working with C# for a while and trying to get more familiar with Java. So I'm trying to migrate some of the basic patterns I use on daily basis in C# even only to understand the gap between JVM and dotnet and figure out how to deal with them. Here is the first problem I encountered - an option type - somethiong which is quite easy to achieve in many languages i.e. Koltlin:
sealed class Option<out T : Any> {
object None : Option<Nothing>()
data class Some<out T : Any>(val value: T) : Option<T>()}
因此我可以轻松创建地图函子:
so I can easily create a map functor:
fun <T : Any, B : Any> Option<T>.map(f: (T) -> B): Option<B> =
when (this) {
is Option.None -> Option.None
is Option.Some -> Option.Some(f(this.value))}
这是我可以在Java中实现的东西吗?我不担心缺少扩展方法,我可以不用那个,但是如何在不依赖于未经检查的演员的情况下执行实际的类型匹配呢?至少这就是IntelliJ抱怨的...
Is this something I can achieve in Java? Im not concerned about the lack of extentions methods, I can leave without that, but how to perform the actual type matching without having to rely on an unchecked cast? At least thats what IntelliJ is complaining about...
推荐答案
在您提到的特定情况下,以下方法将起作用:
in the specific case you mentioned, the following would work:
- (如@oldcurmudgeon所述)
java.util.Optional
它还具有一个map
函数. - 还有guava库,它具有
com.google.common.base.Optional
,以备Java 7及以下版本使用.与map
等效的是
- (as @oldcurmudgeon mentioned)
java.util.Optional
it also has amap
function. - there's also the guava library, that has
com.google.common.base.Optional
, in case you want it for java version 7 and below. the equivalent ofmap
here would be thetransform
function.
Java没有模式匹配.您可以使用访客模式最接近Java中的模式匹配.
Java doesn't have pattern matching. The closest you can get to pattern matching in Java is with the visitor pattern.
用法:
UnionType unionType = new TypeA();
Integer count = unionType.when(new UnionType.Cases<Integer>() {
@Override
public Integer is(TypeA typeA) {
// TypeA-specific handling code
}
@Override
public Integer is(TypeB typeB) {
// TypeB-specific handling code
}
});
样板代码:
interface UnionType {
<R> R when(Cases<R> c);
interface Cases<R> {
R is(TypeA typeA);
R is(TypeB typeB);
}
}
class TypeA implements UnionType {
// ... TypeA-specific code ...
@Override
public <R> R when(Cases<R> cases) {
return cases.is(this);
}
}
class TypeB implements UnionType {
// ... TypeB-specific code ...
@Override
public <R> R when(Cases<R> cases) {
return cases.is(this);
}
}
这篇关于Java中的联合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!