2016-09-26 60 views
1

考慮:類型成員瓦特/隱

// type-class 
trait Eq[A] 

class MyInt 
object MyInt { 
    implicit val myIntEq = new Eq[MyInt] {} 
} 

sealed trait Something { 
    type A 
    implicit val x: Eq[A] 
} 

case object SomethingImpl extends Something { 
    override type A = MyInt 
    override implicit val x = MyInt.myIntEq 
} 

然後,我用的類型成員通過的implicit

scala> def f(s: Something): Eq[s.A] = { 
    | implicit val x: Eq[s.A] = s.x 
    | x 
    | } 
f: (s: Something)Eq[s.A] 

然而,我的直覺告訴我,這是有些笨拙有帶來的隱性通過implicit val ...進入範圍。

也許我應該在Something的伴侶對象中定義f函數?

什麼是定義此f函數的標準方法?

+2

你的'f'函數的例子似乎過於簡化了,因爲對於當前的信息,我會簡單地將它實現爲'= s.x'。 – sjrd

+1

你可以'輸入s.x'。 –

+0

@ Jasper-M這是答案,而不是評論。 –

回答

2

如果你想把某種隱含的東西帶進範圍,你通常是import吧。

def f(s: Something) = { 
    import s.x 
    ??? 
} 
+0

是否可以在'Something'伴侶中寫入'f'?我嘗試過,隱式地[object f] {def f(x:Something)= {Eq [x.A]]; ??? } }',但沒有編譯。 –