Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

scala By-name parameter on a anonymous function

I'm struggling to write an anonymous function with by-name parameter. Here is what i tired.

val fun = (x: Boolean, y: =>Int) => if(x) y else 0

This fail with following error.

Error:(106, 31) identifier expected but '=>' found.
    val fun = (x: Boolean, y: =>Int) => if(x) y else 0
                              ^
Error:(109, 3) ')' expected but '}' found.
  }
  ^

How ever same code as a standard function works.

  def fun1(x: Boolean, y: =>Int) = if(x) y else 0

Any pointers ?

---------------Edit-----------------

I had a two part problem. senia answer solved the initial case. Suppose I have a function takes a function.

  def xxx[A,B](f:(A,=>B)=>B)={}

As per senia solution it works.

val fun: (Int, =>Boolean) => Boolean = (x, y) => y
xxx[Int,Boolean](fun)

However I wanna get rid of the intermediate fun and call xxx with anonymous function. Doing

xxx((Int, =>Boolean) => Boolean = (x, y) => y) 

Will not work. Any ideas how to do this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could specify type of anonymous function, instead of types of parameters like this:

val fun: (Boolean, => Int) => Int = (x, y) => if(x) y else 0

scala> fun(false, {println("!"); 2})
res1: Int = 0

scala> fun(true, {println("!"); 2})
!
res2: Int = 2

=> Int is not a correct type name, it's a special syntax for by-name parameters in parameters block of method declaration or anonymous function type.

See SLS 4.6 Function Declarations and Definitions

ParamType ::= Type
            | ‘=>’ Type
            | Type ‘*’

In case you don't want to assign anonymous function to variable you could either use type inference like this:

xxx[Int, Boolean]{ (x, y) => y }

Or specify its type this way:

xxx({ (x, y) => y }: ((Int, => Boolean) => Boolean))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...