VB_
VB_

Reputation: 45722

Scala: break outer function from inner function

What I have

I have a function below (I can't change outer function)

def outer(x: Int, inner: Int => Boolean): Boolean = {
    inner(x)
    false
} 

What I want

Define inner function in such way that: if (x == 10) outer function return true

def inner(x: Int): Boolean = {
  if (x == 10) OUTER_FUNCTION_SHOULD_RETURN_TRUE!!!
  else false
}

outer(10, inner) // TRUE!!

Question

How can I do it?

Edit:

I use the next trick:

// If inner return true at least once, then outerWraper return true
def outerWrapper(x: Int, inner: Int => Boolean): Boolean = {
  var flag = false

  def inner2(e: Int): Boolean = {     
    if (!flag) flag = inner(e)
    inner(e)
  }

  outer(x, p2)  
  flag
}

Can I avoid using var flag, but use val insted? As I understand var is a bad style in Scala

Upvotes: 1

Views: 496

Answers (3)

蘇哲聖
蘇哲聖

Reputation: 795

My method is here:

import scala.util.control.Breaks
def outer(x: Int, inner: Int => Boolean): Boolean = {
  Breaks.breakable {
    inner(x)
    return false
  }
  true
}

def inner(x: Int): Boolean = {
  if (x == 10) Breaks.break()
  else false
}

println(outer(10, inner)) // TRUE!!

Upvotes: 0

Shrey
Shrey

Reputation: 2414

If you can define your wrapper, you probably can avoid using var

def outerWrapper(x: Int, f: Int => Boolean): Boolean = {
    if (f(x)) true
    else outer(x, f)
}

Then you can pass inner method to outerWrapper method

outerWrapper(10,inner)

Upvotes: 1

David
David

Reputation: 3422

In Scala, the last expression is returned unless you use the return keyword. In your case, the function outer always returns false.

Since you just wrap the inner function you could remove the false:

def outer(x: Int, inner: Int => Boolean): Boolean = {
  inner(x)
}

def inner(x: Int): Boolean = {
  if (x == 10) true else false
}

Or, even shorter:

def inner(x: Int): Boolean = {
  x == 10
}

This would return the returned expression of the inner function, namely true if x == 10, otherwise false.

Upvotes: 1

Related Questions