Drew H
Drew H

Reputation: 4739

Why put a generic type next to a function?

When I look at Scala libraries I see code like this. Why put test [A] .

   def test[A](block : Int => Unit) : Unit = {  
        block(10)
    }     

    test { u =>

        println(u)        
    }

This is just as valid I suppose. It runs the same way.

 def test(block : Int => Unit) : Unit = {   
            block(10)
        }   

I've just been curious what the reasoning(or design pattern) is behind it. Thanks.

Upvotes: 2

Views: 175

Answers (2)

Brian Hsu
Brian Hsu

Reputation: 8821

When there a generic type next to the function, it means that the function is a generic function.

The following is a very simple example:

// generic functions which returns type of `A`
def test1[A](x: A) = x
def test2[A](x: => A) = { println("Hello"); x }

val x1 = test1(1)
// x1: Int = 1

val x2 = test1("Hello World")
// x2: java.lang.String = Hello World

val x3 = test2(123.4)
// Hello
// x3: Double = 123.4

val x4 = test2("Test2")
// Hello
// x4: java.lang.String = Test2

As you can see, the return type of test1 and test2 are determined by the type of their arguments.

The following is another use case.

// We could implement `map` function ourself.
// We don't care about what type of List contains,
// so we make it a generic function.
def map[A, B](xs: List[A], f: A => B): List[B] = {
    var result: List[B] = Nil
    for (i <- xs) {
        result ++= List(f(i))
    }
    result
}

// Now use can map any type of List to another List.
map(List("1", "2", "3"), (x: String) => x.toInt)
//res1: List[Int] = List(1, 2, 3)

Upvotes: 1

kiritsuku
kiritsuku

Reputation: 53348

The type parameter A makes no sense here because it is not used.

def test[A](block: Int => A): A = block(10)

Here A specifies the return type.

Upvotes: 7

Related Questions