Type annotation on _ variable

Is there a syntax for putting a type annotation on _ as in the following?

seq.fold(0)(_:Int + _:Int)

In particular, I’m trying to write the following.

def sumOfProducts[A](seq:Seq[Seq[A]], plus:(A,A)=>A, zero:A, times:(A,A)=>A, one:A):A = {
  seq.foldLeft(zero) {
    (sum, gamma) => plus(sum, gamma.fold(one)(times))
  }
}

sumOfProducts(
  Seq(Seq( 1, 2, 3), Seq(10, 20, 30), Seq(100, 200, 300)),
  plus=(_:Int + _:Int),
  zero=0,
  times=(_:Int * _:Int),
  one=1)

scala> (: Int) + (: Int)
res0: (Int, Int) => Int = $$Lambda$789/1386677799@6124287a

1 Like

Short answer, as given by @curoli: parenthesize.

(_: Int) + (_: Int)

I’d prefer specifying the type parameter directly rather than specifying parameter types to help the compiler infer this type parameter, though:

sumOfProducts[Int](
  Seq(Seq(1, 2, 3), Seq(10, 20, 30), Seq(100, 200, 300)),
  plus = _ + _,
  zero = 0,
  times = _ + _,
  one = 1
)

Furthermore, you can partition your function signature into multiple parameter lists: first those that are likely to be inferred unambiguously, then the rest that can take advantage from the inference of the first parameter list.

def sumOfProducts[A](
  seq: Seq[Seq[A]])(
  plus: (A, A) => A, zero: A, times: (A, A) => A, one: A
): A

sumOfProducts(
  Seq(Seq(1, 2, 3), Seq(10, 20, 30), Seq(100, 200, 300)))(
  plus = _ + _,
  zero = 0,
  times = _ + _,
  one = 1
)
1 Like

That’s clever. Thanks.

@curoli, I’ve never seen the (:Int) syntax, and I’d never have guess it.

That’s an artifact of forum programming. @curoli wrote (_: Int) + (_: Int) but forum parsed that as (: Int) + (: Int). Note that the the _ signs are gone and text between them is made italic.

1 Like

yes, but it would be an interesting notation, nonetheless.

Interesting. The Scala forum does not support posting Scala code.

So I should have responded: you have to write open-parenthesis, underscore, colon, Int, close parenthesis, plus, open parenthesis, underscore, colon, Int, close parenthesis.

Maybe we should in parallel use a Google group to post the code, and then we can post here links to the code. Not to many at once, of course, because I think the forum doesn’t want you to post more than two links, either.

1 Like

It does, but you have to precede it and follow it with triple-backticks (```) on an otherwise empty line; I don’t think you’re doing so. (This is, for example, what @sangamon is doing above.) It doesn’t work perfectly, but it’s much better than nothing.

Trying to post Scala code through email …

Inline code with single backticks: println("Hello World!"), (_: Int) + (_: Int)

Inline code with triple backticks: println("Hello World!"), (_: Int) + (_: Int)

Multiline code with triple backticks:


class Greeter(who: String) {

def greet(): Unit = println(s"Hello, $who!")

}

(_: Int) + (_: Int)