Home > OS >  Could not infer type of parameter
Could not infer type of parameter

Time:12-30

I have created MyList abstract class to implement the list, the reason for not using already present list implementation is I am learning scala and this was exercise for the same course.I am writing a zipWith function to create a new list with concatenation of individual items for example:

list 1: list = [1,2,3]
list 2: listOfStrings = ["Hello", "This is", "Scala"]

and I am expecting output like: [1-Hello, 2-This is, 3-Scala]

I wrote zipWith function as mentioned below:

  override def zipWith[B, C](list: MyList[B], zip: (A, B) => C): MyList[C] = {
    if(list.isEmpty) throw  new RuntimeException("Lists do not have the same length")
    else new Cons(zip(h, list.head), t.zipWith(list.tail, zip))
  }

And I am trying to call this function using this statement:

println(list.zipWith[String, String](listOfStrings, (Int,String)=>_ "-" _))

But I am getting an error:

I could not infer the type of the parameter _$3 of expanded function:
(_$3, _$4) => _$3   "-"   _$4.

Type for this variable is clearly mentioned as Int still I am getting this error. This could be solved using:

println(list.zipWith[String, String](listOfStrings, _ "-" _))

I am not able to understand why earlier statement fails, even after giving the type for the required variable

CodePudding user response:

The syntax (Int,String)=>_ "-" _ doesn't mean what you think.

It represents a function taking two parameters with some name but unknown type: (Int: ???, String: ???) => _ "-" _.

Thus the compiler is raising an error because it indeed have no clue about the types.

You should either:

  • write it with explicit variable names: (i: Int, s: String) => s"$i-$s". (Notice the usage of interpolation which is recommended over adding int and string),
  • or declare the function separately like this: val f: (Int, String) => String = _ "-" _.

CodePudding user response:

I think the compiler is confused on which variable to match each underscore. This explicit expression works for me:

println(list.zipWith[String, String](listOfStrings, (a:Int, b:String) => a "-" b))
  • Related