Scala: why can't I filter my Int list correctly with a placeholder? for example: myList.filter (_: Int => _% 5 == 0)

I have a little problem with placeholder syntax in Scala. So I have a simple list of numbers:

myList = List(13, 24, 10, 35)

firstly, I tried to filter this list as follows

myList.filter(_ => (_ % 5) == 0)

and the compiler complains, because it cannot deduce the type of the parameter:

error: missing parameter type for expanded function ((x$2) => x$2.$percent(5))

okay, no problem: I added a type for the parameter

myList.filter(_:Int => _ % 5 == 0)

Now the compiler gives me this:

identifier expected but integer literal found.
       someNumbers.filter(_:Int => _ % 5 == 0)
                                       ^

Do you guys know why I have this weird mistake? I really do not understand...

thanks in advance,

+3
source share
3 answers

You have no idea, but this:

identifier expected but integer literal found.
       someNumbers.filter(_:Int => _ % 5 == 0)
                                       ^

- ! , , , - , . -, , :

someNumbers.map(_: Int => _ <:< Any)

, , ( ): % <:, 5 Any ( - ).

, - , . :

someNumbers.map(_ + 1)
someNumber.map(_) // does not compile

- :

someNumbers.map(x => x + 1)
x => someNumbers.map(x)

, x , . , , x, , . , , , .

, : Int, , .

, , . :

someNumbers.map(x => x + 1) // valid code
someNumbers.map((x: Int) => x + 1) // valid code
someNumbers.map(x : Int => x + 1) // "invalid" code

, "", , ! , , :

val f: Int => Int = x => x

=>, , ! , Int => Int, Function1[Int, Int]. , => Int => Int .

x => x () new Function1[Int,Int] { def apply(x: Int) = x }. => .

, someNumbers.filter(_: Int => _ % 5 == 0). :

someNumbers.filter(_: Int => _ % 5 == 0) // gets rewritten as
(x: Int => _ % 5 == 0) => someNumbers.filter(x)

, Int => _ % 5 == 0 . , => , 5! ?

-, . Scala, : infix. :

someNumbers.map(_: Int => _ <:< Any)
someNumbers.map(_: Int => <:<[_, Any])

, 2 * 2 2.*(2), Int Map String Map[Int, String]. , , % - , , _.

, , _, , : ! , . :

(x: Function1[Int,<:<[t, Any] forSome { type t }]) => someNumbers.map(x)

( *):

new Function1[Function1[Int, <:<[t, Any] forSome { type t }], List[<:<[q, Any] forSome { type q }]] { 
  def apply(x) = someNumbers.map(x) 
}

, , , ?: -)

(*) , , t q , .

+16

:

val myList = List(13, 24, 10, 35)
myList.filter(x => (x % 5) == 0)

_ - myList.map(_ + 5) , myList.map(x => x + 5). , myList.map(_ => _ + 5), " myList x => x 5".

- - . myList.map(_ => 1) " 5". , , , _ => .

myList.filter(x => (x % 5) == 0) " x myList, , (x % 5) == 0".

+6

What about:

myList.filter(_ % 5 == 0)
+3
source

All Articles