Need help for below Lab code

Write a function add , which takes two integer variables x and y and returns their sum as output in which y is an implicit parameter , and also declares the implicit parameter in the main function as 7 . Then, write a function greet which takes two strings s1 and s2 , where s1 is an implicit parameter with value as Name . On taking the string input from the command line, the program must print s1 : s2

object ImplicitParams2 extends App {
val input1 : String = args(0)
val input2 : Int = args(1).toInt
def add(x: Int = input2)(implicit y: Int =7) = x +y
def greet(implicit s1: string = “name”)(s2: string = input1) = s1 + “:” s2
println(greet(input1))
println(add(input2))
}

but its not working, can someone please help

please help i am struck and not able to move forward in lab

What do you mean by “it’s not working”? Do you get an error? If so, can you post that error? Otherwise, can you describe what is wrong?

1 Like

While executing it with input as JOHN 5, expected result is Name : John 12 but I am getting JohnJohn 12. Not sure what is wrong, can you please help to check the code and suggest the correction

If you take a closer look to your code, you will see that the problem is trivial.

// The implicit parameter is the first.
def greet(implicit s1: string = “name”)(s2: string = input1) = s1 + “:” s2

// Here you are overriding the implicit parameter with an explicit parameter.
println(greet(input1))
// Thus:
greet(input1)(s2: string = input1) = input + “:” input

You can fix it by doing this:

// Do not pass anything in the first parameter group so it uses the implicit value.
println(greet()(input1))

However, this feels weird and it is more common for implicits to be the last parameter group, especially to do not use an empty parameter list.
Also, this:

"And also declares the implicit parameter in the main function as 7"

Which makes me feel like a better version of the code would be:

object ImplicitParams2 extends App {
  implicit val num: Int = 7

  val input1: String = args(0)
  val input2: Int = args(1).toInt

  def add(x: Int)(implicit y: Int): Int = x +y
  def greet(s2: String)(implicit s1: String = “name”): String = s"${s1} : ${s2}"

  println(greet(input1))
  println(add(input2))
}

Thank You it helps :slight_smile:

Hi Are you doing fresco play scala course I am also doing the same lab and stuck on multiple handson .Is there a way we can connect offline…