Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange syntax in lambda expression

Tags:

scala

val (xa, xb) = xs partition ( a > )

What is a > in above code and how is it different from a > _? (assume a is some predefined value)

like image 302
user5248896 Avatar asked Dec 10 '22 13:12

user5248896


2 Answers

Any method that expects a function with some argument can be instead passed a one-argument method and, if the types work out, the method will be automatically converted.

So these all are valid:

class C { def go(i: Int) = -i }
val c = new C
List(1,2,3).foreach( println )
List(1,2,3).map( c go )

So, either a has the method > defined, or it can be implicitly converted to something with a > method. For example, this works:

List(1,2,3).partition(2 >)

because (EDIT: one would think this would be true....) there is an implicit conversion from Int to RichInt (the same one that gives you .toFloat and such), and RichInt has a > method defined. partition expects a function that takes Int and returns Boolean and 2 > is a method that takes Int and returns Boolean. So the conversion happens automatically.

(EDIT: but as @Lukas Rytz points out, it's even more tricky than that, because the compiler realizes that it can treat primitive ints specially, so even though > is not really a method on the object 2, because 2 is not an object, and primitives do not have methods, the compiler recognizes that deferring to RichInt would be slower. So, in fact, it just writes a method with the correct bytecode.)

Only if the correct conversion does not happen automatically (because of ambiguity, for example, or because you want to assign it to a variable) do you need to use _ to create a function out of a method. (And then it is not always exactly clear whether you are using _ to convert from method to function, or using _ as a placeholder for the input; fortunately, the result is the same either way.)

like image 130
Rex Kerr Avatar answered Dec 26 '22 00:12

Rex Kerr


It is not different at all, it's just a shorter version.

scala> val a = 10
a: Int = 10

scala> val xs = List(1, 2, 3, 4, 5, 11, 12, 13, 14, 15)
xs: List[Int] = List(1, 2, 3, 4, 5, 11, 12, 13, 14, 15)

scala> val (xa, xb) = xs partition ( a > )
xa: List[Int] = List(1, 2, 3, 4, 5)
xb: List[Int] = List(11, 12, 13, 14, 15)
like image 30
Randall Schulz Avatar answered Dec 25 '22 23:12

Randall Schulz