如何将scala类作为对象传递给函数参数?

时间:2019-03-01 02:16:48

标签: scala class reference arguments parameter-passing

如何运行refint1函数?我尝试过var x = new RefInt(5) ,然后做scala> argpass.refint1(x),但在控制台中遇到了found: RefInt, required : argpass.RefInt => Unit错误。

object argpass{
       class RefInt (initial : Int) {
         private var n : Int = initial
         def get () : Int = n
         def set (m : Int) : Unit = { n = m}
        }
        def refint1 ( f: RefInt => Unit) : (Int, Int, Int) = {
          var x = new RefInt(5)
          val first = f(x)
          val firstget = x.get
          val sec = f(x)
          val secget = x.get
          val third = f(x)
          val thirdget = x.get
          (firstget, secget, thirdget)
    }

//如何运行refint1函数?

1 个答案:

答案 0 :(得分:1)

正如路易斯在评论中所说,f返回Unit,这基本上是无效的。这应该可以解决您的问题:

class RefInt(initial: Int) {
  var n: Int = initial
  def get(): Int = n
  def set(m: Int): Unit = { n = m }
}

def refint1(f: RefInt => Unit): (Int, Int, Int) = {
  var x = new RefInt(5)  
  f(x)
  val firstget = x.get
  f(x)
  val secget = x.get
  f(x)
  val thirdget = x.get

  (firstget, secget, thirdget)
}

话虽这么说,我认为您可以稍微改善设计。这是解决同一问题的另一种方法:

case class RefInt(initial: Int)

def refInt1(initial: RefInt, f: RefInt => RefInt) : (Int, Int, Int) = {  
  val x0 = f(initial)
  val x1 = f(x0)
  val x2 = f(x1)

  (x0.initial, x1.initial, x2.initial)
}

println(refInt1(RefInt(5), ri => ri.copy(ri.initial * 2)))