2016-11-08 81 views
0

我有我自己的類斯卡拉 - 錯誤:值最大是不是我的自定義類的成員

class Foo { 
MyCustomClass value; 
... 
} 

其中包括MyCustomClass的是java的枚舉具有以下特徵:

enum MyCustomClass{ 
    ONE(1), 
    TWO(2), 
    THREE(3) 

    private int nominal; 

    MyCustomClass(int nominal) { 
     this.nominal = nominal; 
    } 

    public int nominal() { 
     return nominal; 
    } 
} 

爲此我定義排序中:

implicit val myCustomClassOrdering = new Ordering[Foo] { 
    override def compare(c1: Foo, c2:Foo): Int = { 
     c1.value.nominal.compareTo(c2.value.nominal) 
    } 
} 
import myCustomClassOrdering ._ 

,然後我可以使用函數max爲對象的序列ofMyCustom類類型。但我得到試圖reduceOption功能使用max溫控功能的錯誤

val l = List[Foo](...) 
l.reduceOption(_ max _) 

得到錯誤信息:value max is not a member of ...

我應該怎麼做才能夠在reduceOptionmax功能使用它呢?

回答

0

最大方法委託MyCustomClass。爲Foo添加排序或添加另一個方法,該方法根據MyCustomClass值上的最大方法調用的結果返回Foo對象。

def op(x: Foo,y: Foo):Foo = { 
    if((x.value max y.value) == x.value) x 
    else y 
    } 

    val b = l.reduceOption(op(_,_)) 
+0

修正了他的錯誤,請刪除 – midor

+0

哦,對不起,我試圖簡化,但確切的情況是更復雜的,我做了一些問題的變化。 – Dmitrii

0
object FooExtension { 
    implicit class RichFoo(c:Foo) { 
     def max(c2:Foo) = { 
      if(c.value.nominal > c2.value.nominal) c else c2 
     } 
    } 
} 

import FooExtension._ 

現在,它的工作原理,但我不知道是否有更爲清晰的解決方案,我可以依靠內置的max和排序功能。

相關問題