0

How do I run the refint1 function? I've triedvar x = new RefInt(5) and then doing scala> argpass.refint1(x)but get a found: RefInt, required : argpass.RefInt => Unit error in the console.

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)
    }

//How do i run the refint1 function?

1
  • First f is a function from RefInt to Unit (equivalent of Java's void). Thus, you need to pass a function, not a value. - Second, since the function returns an Unit, storing its result _(in first, second & third) is meaningless. - Third, x, even if muted internally by f, is not reassigned, thus it may (should IMHO) be a val. - Finally you can call refint1 like this: refint1 { ri => ri.set(i); i += 1 } where var i = 0. Commented Mar 1, 2019 at 3:02

1 Answer 1

2

As Luis said in the comments, f returns Unit, which is basically void. This should solve your problem:

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)
}

That being said, I think you can improve your design a little bit. Here's a different approach to solve the same problem:

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.