このコードは論理的ですが、コンパイラが間違った型の述語isBondAssetについて不平を言っているのはなぜですか?java 8述語型の不一致、このコードは論理的です。
「資産を拡張する任意のタイプの述語」は、「資産を拡張する任意のタイプのスーパータイプの述語」か、間違っていますか?私は間違っていないですので、もしそれがその主な理由の
Predicate<? super Asset> isBondAsset
一つでなければなりませんStream#filter
/**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to each element to determine if it
* should be included
* @return the new stream
*/
Stream<T> filter(Predicate<? super T> predicate);
によると、Predicates
を使用する可能性が既にのために定義されて
private static class Asset
{
public enum AssetType
{
BOND,
STOCK;
}
private final AssetType type;
private final int value;
public Asset (AssetType type, int value)
{
this.type = type;
this.value = value;
}
public AssetType getType()
{
return type;
}
public int getValue()
{
return value;
}
}
private static class AssetUtils
{
public static int totalBondAssetValues (Collection <? extends Asset> assets)
{
Predicate<? extends Asset> isBondAsset = asset -> Asset.AssetType.BOND.equals(asset.getType());
return assets.stream().filter(isBondAsset).mapToInt(Asset::getValue).sum();
}
}
なぜ「述語」を使用しませんか?これは 'Asset'のポリモーフィックで、' Asset'のサブタイプを受け入れます。それはあなたが望むものではありませんか? –
はい私は@ Jean-BaptisteYunèsを知っていますが、私は可能な限り自分のタイプに柔軟性を持たせたい – marsouf
次にhttps://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in- Java –