Say I define a class with ordering as below:
case class C(i: Int)
implicit def ordering[A <: C]: Ordering[A] = new Ordering[A] {
def compare(c1: A, c2: A): Int = c1.i.compareTo(c2.i)
}
I get the following info from the compiler:
Convert expression to Single Abstract Method less... (Ctrl+F1) Inspection info: Checks if an expression can be converted to SAM (Single Abstract Method). Before: new Thread(new Runnable { override def run() = println() }
After: new Thread(() => println())
But it is not obvious to me what the correct syntax in this case is? I have tried the code below but it does not compile:
implicit def ordering[A <: C]: Ordering[A] = new Ordering[A]((c1: A, c2: A) => c1.i.compareTo(c2.i))
The correct syntax is:
implicit def ordering[A <: C]: Ordering[A] = (c1: A, c2: A) => c1.i.compareTo(c2.i)
Single Abstract Methods are used when you create an instance of a trait with one and only one method.
SAM comes from java8, and were introduced in scala 2.12:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.