Chris Leishman
Chris Leishman

Reputation: 1798

Scala type parameters for objects

This is related to this question, however I can't see how using existential types would help in my case.

I'm trying to achieve the following:

type MonadicArithmeticFunc[S] = (Int, S) => (Int, S)

object addOne[S] extends MonadicArithmeticFunc[S] {
  def apply(n: Int, s: S): (Int, S) = (n + 1, s)
}

val state = Seq.empty[Int]
println(addOne(4, state))

However this doesn't work as one cannot add a type parameter to an object. I tried using an existential type also:

object addOne extends MonadicArithmeticFunc[_] {
  def apply[S](n: Int, s: S): (Int, S) = (n + 1, s)
}

But of course that doesn't work either, as the apply method isn't what takes the type parameter in Function2.

I could use a basic def:

def addOne[S](n: Int, s: S): (Int, S) = (n + 1, s)

except I'd have to declare that in a package object to get the same scoping. Any other ideas?

Upvotes: 0

Views: 175

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170859

It simply doesn't make sense to have type parameters (or constructor parameters, for that matter) for an object, because addOne[Int] and addOne[String] would be (presumably) different objects, but the keyword object means there only should be one object. You could have

class addOne[S] extends MonadicArithmeticFunc[S] {
  def apply(n: Int, s: S): (Int, S) = (n + 1, s)
}

object addOne {
  def apply[S] = new addOne[S]
}

if you really need MonadicArithmeticFunc for some reason. But as Alexlv says,

object addOne {
  def apply[S](n: Int, s: S) = (n + 1, s)
}

would normally be preferable.

Upvotes: 2

Related Questions