java 联合,Java中的联合类型

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 {

object None : Option()

data class Some(val value: T) : Option()}

so I can easily create a map functor:

fun Option.map(f: (T) -> B): Option =

when (this) {

is Option.None -> Option.None

is Option.Some -> Option.Some(f(this.value))}

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:

(as @oldcurmudgeon mentioned) java.util.Optional it also has a map 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 of map here would be the transform function.

Java doesn't have pattern matching. The closest you can get to pattern matching in Java is with the visitor pattern.

usage:

UnionType unionType = new TypeA();

Integer count = unionType.when(new UnionType.Cases() {

@Override

public Integer is(TypeA typeA) {

// TypeA-specific handling code

}

@Override

public Integer is(TypeB typeB) {

// TypeB-specific handling code

}

});

boilerplate code:

interface UnionType {

R when(Cases c);

interface Cases {

R is(TypeA typeA);

R is(TypeB typeB);

}

}

class TypeA implements UnionType {

// ... TypeA-specific code ...

@Override

public R when(Cases cases) {

return cases.is(this);

}

}

class TypeB implements UnionType {

// ... TypeB-specific code ...

@Override

public R when(Cases cases) {

return cases.is(this);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值