This weird type [T *]

For example, I have the following function, which combines the beginning and the end, creating all possible variants of concatenation as a result:

def mixer1(begin: String, beginings: String*)(end: String, endings: String*) =
  for (b <- (begin +: beginings); e <- (end +: endings)) yield (b + e)

Actually, which function is not impotent, I want to rewrite it like this:

  def mixer2(begin: String, beginings: String*):Function2[String, Seq[String], Seq[String]] = {
    return new Function2[String, Seq[String], Seq[String]] {
      def apply(end:String, endings:Seq[String]) = for(b <- (begin +: beginings); e <- (end +: endings)) yield b+e
    }
  }

Obviously, the second will not work as expected, because applying the second parameter is of type Seq [String], but not String * (no matter how they are compiled into Seq [String]):

scala> mixer1("a","b")("c","d")
res0: Seq[java.lang.String] = ArrayBuffer(ac, ad, bc, bd)

scala> mixer2("a","b")("c","d")
<console>:10: error: type mismatch;
 found   : java.lang.String("d")
 required: Seq[String]
       mixer2("a","b")("c","d")

How can I (if I can) override the mixer2 function?

+3
source share
4 answers

Try as follows:

def mixer2(begin: String, beginings: String*) = {
    new ((String, String*) => Seq[String]) {
      def apply(end: String, endings: String*) = for(b <- (begin +: beginings); e <- (end +: endings)) yield b+e
    }
}

mixer2, . , return , , (, , Scala). A => B Function, String*. apply, .

+3

:

def mixer2 = mixer1 _
+2

,

implicit def toSeq[T](x: T): Seq[T] = List(x)

,

mixer2("a","b")("c","d","e")

, , [T] Seq [T]. T * , ( "c", "d", "e" ) 3 . , .

, , , . , @Debilski - .

0
source

You can run away without even giving an intermediate return type.

def mixer2(begin: String, beginings: String*) = new {
  def apply(end: String, endings: String*) =
    for (b <- (begin +: beginings); e <- (end +: endings)) yield b+e
}

People will try to tell you that this is related to thinking. Surprisingly, this is not so.

0
source

Source: https://habr.com/ru/post/1776870/


All Articles