Type parameters applied to Scala Function

后端 未结 6 1018
遇见更好的自我
遇见更好的自我 2021-01-23 08:35

I am trying to understand the type parameters when applied to a function.

I would like to use Generic Types in the below method but using String and Int for my understa

6条回答
  •  余生分开走
    2021-01-23 09:01

    It's good trying to make your own examples, but have you tried any examples from books, articles or tutorials? There's probably a good one in Scala for the Impatient by Cay Horstmann.

    Here's a decent example from the Tour de Scala:

    def listOfDuplicates[A](x: A, length: Int): List[A] = {
      if (length < 1)
        Nil
      else
        x :: listOfDuplicates(x, length - 1)
    }
    

    Sometimes you can omit the type parameter, but let's ignore that for now and declare the types explicitly:

    listOfDuplicates[Int](43, 5) // Should give a list with 43 five times
    listOfDuplicates[String]("Hello, world! ", 3) // "Hello, world!" thrice
    listOfDuplicates[(Int, Int)]((0, 1), 8) // The pair (0, 1) eight times
    

    This shows that A can be Int, String, (Int, Int) or just about anything else we can think of. Not sure you'd ever have a practical need for this, but you can even do something like this:

    def wrapLength(str: String): Int = str.length
    
    listOfDuplicates[String => Int](wrapLength(_), 2)
    

    Here's a Scastie snippet in which you can play around with this.

提交回复
热议问题