Home > OS >  Why I get a () when I running my Scala code?
Why I get a () when I running my Scala code?

Time:06-24

object test {
  def multBylarge(input: Array[Int]): Int = {
    var result=0
    var lst: List[Int]=List()
    if(input.length == 0) result =1
    else
      for(elements <- input) {
        lst = lst :  elements
      }
    var newlst = lst.sortWith(_ > _)
    result  = newlst(0) * newlst(1)
    result
  }

  def check2(input: Array[_]) = input.foreach {
    case _:Int => multBylarge(_)
    case _:Double => "this is a double array"
    case _:Float => "this is a float array"
    case _=> "this is not a value"
  }

  def main(args: Array[String]): Unit = {
      println(check2(Array(1,3,5,1,3,4)))
  }
}

this is my code, I just have no idea. It will be appreciated if anyone can help me with it. And I am not familiar with scala code, so if there has any other problem, please let me know.

CodePudding user response:

Scaladoc is your friend. foreach has return type of scala.Unit (see also) which has only one value - ():

def foreach[U](f: (T) => U): Unit

Apply f to each element for its side effects.

So actual signature of your method is def check2(input: Array[_]): Unit

CodePudding user response:

You can do the following:

  1. Update check2 match on input rather then foreach (since multBylarge requires a array input anyway, foreach wouldn't work here since it iterates over every item in the array then tries to apply it to multBylarge)
  2. Wrap result in a Either (You can think if it as Left = Failure and Right = Successful result)
  3. Then match on the result in the main function to pretty print the result/error
object test {
  def multBylarge(input: Array[Int]): Int = {
    var result=0
    var lst: List[Int]=List()
    if(input.length == 0) result =1
    else
      for(elements <- input) {
        lst = lst :  elements
      }
    var newlst = lst.sortWith(_ > _)
    result  = newlst(0) * newlst(1)
    result
  }

  def check2(input: Array[_]): Either[String, Int] = input match {
      case ints: Array[Int] => Right(multBylarge(ints))
      case _: Array[Double] => Left("this is a double array")
      case _: Array[Float]  => Left("this is a float array")
      case _.               => Left("this is not a value")
    }

  def main(args: Array[String]): Unit = {
      check2(Array(1,3,5,1,3,4)) match {
       case Right(result) => println(s"Result is $result")
       case Left(error)   => println(s"Failed with $error")
    }
  }
}
  • Related