简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM