Scala does not handle implicitly typed closures for functions:

So basically I want to write a function that can be written as follows:

{ println(_) } =: thing 

Here I want it to actually do thing.=:(println(_)) . Assume that the argument =: has the following implementation:

 def =:(block : Int => Any) { block(5) } 

So I try to call it higher, and I get:

 <console>:10: error: type mismatch; found : Unit required: Int => Any println(_) =: thing 

Then I will try to do this:

 thing.=:(println(_)) 

This way I get a nice 5 printed on the terminal. Then I tried this:

 { value => println(value) } =: thing 

This failed again and informed me that there is a "missing parameter type". I assume this is because Scala tries to parse / compile the function argument first in this case and not guess the type like it (I guess completely here) when it is called in a more ordinary way (with the point operator).

Can someone shed more light on the problems here, and can also offer a better way to achieve something close to my original goal?

PS Sorry for the title. I will rename it when I have a better understanding of the problem.

+4
source share
2 answers

Type inference works from left to right, even if the symbolic method names of the form #: end up working from right to left. You can use a helper method if you have only one type:

 def let(fi: Int => Any) = fi case class Thing(i: Int) { def =:(f: Int => Any) = f(i) } scala> let(_+2) =: Thing(5) res4: Any = 7 

but this is not a completely satisfactory solution if you have many possible type signatures, because you need to combine the name of the helper method on the left with the desired type on the right.

+6
source

So why not add a parameter type:

 { value:Int => println(value) } =: thing 

I am not an expert at Scala, so I cannot give a deeper explanation of what the opponent cannot do.

+1
source

All Articles