How to simplify scala literal function like this?

I am new to scala and am trying to write a function literal that checks if a given integer is odd or not. my first attempt:

val isOdd = (x:Int) => (x & 1) == 1

it works fine, and since the x parameter appears only once in this function literal, I am tempted to use the "_" notation to simplify it, for example:

val isOdd = ((_:Int) & 1 ) == 1

however, this time the compiler complains:

warning: comparing a fresh object using `== 'will always yield false
val isOdd = ((_: ​​Int) & 1) == 1

What does this warning mean? why does the compiler recognize ((_ :Int) & 1)as a new object, and not a beaten operation, which leads to a value? is there any way to write this function literal using the notation "_"?

+5
5

, Scala

val isOdd = ((_:Int) & 1 ) == 1

, ,

val result = collection.map( _ + 1 )

, lambda

Scala , , . : (_:Int) , , _ placeholder.

:

val isOdd = ((_:Int) & 1 ) == 1
            ^^^^^^^^^^^^^^
            this is the lambda

val result = collection.map( _ + 1 )
                            ^^^^^^^
                            this is the lambda

val result = collection.map(( _ + 1) / 2)
                            ^^^^^^^^
                            this is the lambda
                            and the compiler can't infer the type of the _

val result = somemap.map(( _ + 1) / 2 * _)
                         ^^^^^^^^
                         this is an inner lambda with one parameter
                         and the compiler can't infer the type of the _
                         ^^^^^^^^^^^^^^^^^
                         this is an outer lambda with one parameter

,

_.map(_ + 1)

x => x.map( y=> y + 1 )
+20

:

val isOdd = (_: Int) % 2 == 1

: -)

+10

:

val isOdd = ((_: Int) & 1) andThen (1 ==)
+7

Scala:

  • ((_:Int) & 1 ) (Int) => Int, .
  • then the comparison operator is used ==to compare this function with a value of 1

The function is not equal to the value 1. Therefore, the result false, therefore, your code is equivalent:

val isOdd = false

What you can do is create another anonymous function that does == 1part of your calculation. This is ugly:

val isOdd = ((_: Int) & 1)(_: Int) == 1

This is equivalent to more verbose (and perhaps easier to understand):

val isOdd = (x: Int) => 1 == ((_: Int) & 1)(x)
+2
source

Another approach

val isOdd = (_:Int).&(1) == 1
+1
source

All Articles