In Scala, can I (can I allow SIP) specify only certain parameters like the generic method?

When calling methods with type parameters in Scala, I often try to arrange the code so that the inferencer type can find out about the type parameters and do not need to fill them out. In some cases, it fails, and I must provide them manually.

In most cases this is not a problem, but for methods with several type parameters (for example, for most methods requiring implicit CanBuildFrom), I was wondering if there is a way to help the inferencer type by providing it with only one of the necessary type parameters and asking it to try and guess others. This is similar internally, it should do such things anyway, since it sometimes gives error messages of the form "expected type A[B, ?], but received A[C, D]", which would mean two type parameters A, he could recognize the first B, but does not have information about the second.

Use case: Tomaszs question where is this code:

def firstAndLast[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): That = {
  val b = cbf(seq)
  b += seq.head
  b += seq.last
  b.result
}

cannot be called with List("abc", "def") map firstAndLast, but it will work:

List("abc", "def") map firstAndLast[String, Char, String]

: inferencer, CC String, A That? - , ,

List("abc", "def") map firstAndLast[CC = String]

List("abc", "def") map firstAndLast[String, <guess>, <guess>]

, ; ( , ).

+5
1

, . lambda type, ( ), . :

// Declaring a type alias
type StringMap[Elem] = Map[String, Elem]

// Calling an `def f[M[_]]` but passing a `Map`
f[({type l[A]=Map[String,A]})#l]

// note that f could also be called like this:
f[StringMap]
+1

All Articles