Type parameters applied to Scala Function

后端 未结 6 1062
遇见更好的自我
遇见更好的自我 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:04

    If you want to use generics, first you have to understand that the name of the variable types starts capitalized and they are names, just that so [Int] in your function is the name of the type variable, an example:

    object Main extends App{
        val f: String => Int = s => 4
        println(myfunc(f, "nothing useful"))
    
        def myfunc[A,B](f:A => B, x: A):B =  {
          f(x)
        }
    }
    

    here the names are A and B and the return type is of type B

提交回复
热议问题