[英]In Scala, is it possible to use implicits to automatically override toString?
[英]Unable to override implicits in scala
我正在嘗試學習scalaz,但仍然對scala還是陌生的(現在已經使用了幾個月)。 我真的很喜歡scalaz提供的類型類,並嘗試記錄scalaz中不同功能的不同用例。 現在,我在暗示工作方式和我想做事情的方式方面遇到問題。
這是我想工作的代碼
import scalaz._
import Scalaz._
object WhatIfIWantfFuzzyMatching extends App {
implicit object evensEquals extends Equal[Int] {
override def equal(left: Int, right: Int): Boolean = {
val leftMod = left % 2
val rightMod = right % 2
leftMod == rightMod
}
}
val even = 2
val odd = 3
assert(even =/= odd, "Shouldn't have matched!")
val evenMultTwo = even * 2
assert(even === evenMultTwo, "Both are even, so should have matched")
}
這個想法很簡單。 對於代碼的某些部分,我想要從scalaz提供的Equal [Int]。 在代碼的其他部分,我想重寫一個不太嚴格的Equal [Int]。
現在,我遇到了一個問題,其中scala無法確定要使用哪個隱式:
ambiguous implicit values:
both object evensEquals in object WhatIfIWantfFuzzyMatching of type com.gopivotal.scalaz_examples.equal.WhatIfIWantfFuzzyMatching.evensEquals.type
and value intInstance in trait AnyValInstances of type => scalaz.Monoid[Int] with scalaz.Enum[Int] with scalaz.Show[Int]
match expected type scalaz.Equal[Int]
assert(even =/= odd, "Shouldn't have matched!")
^
看看這里的其他線程,我看到人們說只是更改類型,所以沒有沖突,或者只在需要時才導入,但是在scalaz的===情況下,混合並匹配不同的equals方法,我就是不知道如何將其與編譯器一起使用。
有什么想法嗎?
編輯:這是一個工作示例,可讓您在實現之間切換(感謝@ alexey-romanov)
object WhatIfIWantToSwitchBack extends App {
// so what if I want to switch back to the other Equals?
object modEqualsInt extends Equal[Int] {
override def equal(left: Int, right: Int): Boolean = {
val leftMod = left % 2
val rightMod = right % 2
leftMod == rightMod
}
}
implicit var intInstance: Equal[Int] = Scalaz.intInstance
assert(2 =/= 4)
intInstance = modEqualsInt
assert(2 === 4)
intInstance = Scalaz.intInstance
assert(2 =/= 4)
}
您可以只使用相同的名稱intInstance
(但這意味着您將丟失Monoid
, Enum
和Show
實例)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.