gpt4 book ai didi

java - 如何摆脱对已实现接口(interface)的多余强制转换?

转载 作者:行者123 更新时间:2023-11-30 06:02:23 27 4
gpt4 key购买 nike

假设我有一个界面

public interface ICardSuit {
/**short name*/
public String getName();

/** the colour of this card*/
public ICardColour getColour();
}

我决定用枚举来实现:

public enum  CardSuit implements ICardSuit {
HEART{
@Override
public ICardColour getColour() {
return CardColour.RED;
}
},
SPADE{
@Override
public ICardColour getColour() {
return CardColour.BLACK;
}
},
DIAMOND{
@Override
public ICardColour getColour() {
return CardColour.RED;
}
},
CLUBS {
@Override
public ICardColour getColour() {
return CardColour.BLACK;
}
}
;

@Override
public String getName() {
return this.name();
}
}

我现在想测试它(使用 kotlintest 因为我越来越喜欢它):

class CardSuitTest : FunSpec(){
init {
test("there are exactly four suits"){CardSuit.values().size shouldBe 4}
test("suits implement interface"){CardSuit.values().forEach { it shouldBe instanceOf(ICardSuit::class) }}
test("suits have correct names"){
val suits = CardSuit.values() as Array<out ICardSuit>
suits.forEach { when(it.name){
"HEART" -> it should beTheSameInstanceAs(CardSuit.HEART as ICardSuit)
"SPADE" -> it should beTheSameInstanceAs(CardSuit.SPADE as ICardSuit)
"DIAMOND" -> it should beTheSameInstanceAs(CardSuit.DIAMOND as ICardSuit)
"CLUBS" -> it should beTheSameInstanceAs(CardSuit.CLUBS as ICardSuit)
} }
}
test("suits have correct colours"){
CardSuit.values().forEach { when(it){
CardSuit.HEART,CardSuit.DIAMOND -> it.colour shouldBe CardColour.RED
CardSuit.CLUBS, CardSuit.SPADE -> it.colour shouldBe CardColour.BLACK
} }
}
}
}

我需要转换到 ICardSuit因为如果我不这样做,编译器会提示

None of the following functions can be called with the arguments supplied.

* T.should(Matcher<T>)   where T cannot be inferred for   infix fun <T> T.should(matcher: Matcher<T>): Unit defined in io.kotlintest.matchers

* ICardSuit.should((ICardSuit) → Unit)   where T = ICardSuit for   infix fun <T> T.should(matcher: (T) → Unit): Unit defined in io.kotlintest.matchers

我想保留as Array<out ICardSuit>因为这是确保我只访问接口(interface)属性的最简单方法,

但我真的不喜欢强制转换我正在测试的实例。

我能做些什么吗?

最佳答案

您需要使用匹配器 beSameInstanceAs 是否有具体原因?

你可以这样做:

val suits = CardSuit.values() as Array<out ICardSuite>

suits.forEach {
when (it.name) {
"HEART" -> it shouldBe CardSuit.HEART
"SPADE" -> it shouldBe CardSuit.SPADE
}
}

但是,如果您确实想使用beSameInstanceAs,您可以:

suits.forEach {
when(it.name) {
"HEART" -> it shouldBeSameInstanceAs CardSuit.HEART
"SPADE" -> it shouldBeSameInstanceAs CardSuit.SPADE
}
}

我在这里并没有真正收到编译器的任何提示

关于java - 如何摆脱对已实现接口(interface)的多余强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55103283/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com