St.Antario St.Antario - 1 year ago 95
Scala Question

Is there a way to conciesly write anonymous subtrait with only one abstract method?

When writing tests in

I used the so called
trait which looks as (documentation ommited):

trait Equality[A] extends Equivalence[A] {
def areEqual(a: A, b: Any): Boolean
final def areEquivalent(a: A, b: A): Boolean = areEqual(a, b)

I currently implement it as following

implicit def positionEquality: Equality[SomeType] = new Equality[SomeType] {
override def areEqual(a: SomeType, b: Any): Boolean = b match {
//actual code

But I'd like to write it more concisely... like function literal or some. Is there something like that?

UPD: I could only imagine some implicit conversion, but it looks quite weird as that I will have to bring it into scope explicitly every time I'd like to use it.

Answer Source

In Scala 2.12

implicit def positionEquality: Equality[SomeType] = (a, b) => b match ...

should work. In Scala 2.11 it requires -Xexperimental compiler options (IIRC, there are cases it doesn't work correctly; unfortunately I don't know exactly what they are and if this is one of them, but I wouldn't expect so).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download