elarib
elarib

Reputation: 674

Using Type parameter in Scala Functions

I'm trying to implement the Boolean Type in Scala, and i found an example using this signature :

abstract class Boolean {
   def ifThenElse[T](t : => T , e : => T) : T

   ... }

My questions is :

  1. When we should use the type Parameter after the function name like this funcName[T].

  2. What does t : => T mean ?

Thank you

Upvotes: 0

Views: 125

Answers (1)

Jerry
Jerry

Reputation: 492

As for the first question:

1.When we should use the type Parameter after the function name like this funcName[T]

if you want this function can be used by different type, it's appreciate that put the generic type after function name as funcName[T]. For example, you have a function like this

def myFunction[T](param1: T){/*process*/}

you want to pass the parameter param1 and param2 to myFunction. These two parameters are defined as following

val param1: Int = 10 
val param2: String = "test"

Though param1 and param2 have different types, you can call the function myFunction(param1) and also myFunction(param2)

Then, let's talk about the second question

2.What does t : => T mean ?

It's a by-name parameter. what's it? The following gives you more details:

t: => T has the same meaning as t: () => T, instead of inputing the words () => T, you can choose => T as for t

Another example: if you want to has an assertion, you may define the function like this:

def myAssert(predicate: () => Boolean) = 
    if(!predicate()) throw new AssertionError

then you can use it as following

myAssert(() => 5 > 3)

The usage is so ugly, is it? You may want to use it like this

myAssert(5 > 3)

at this time, the by-name parameter will be on the stage. Just define your function by the help of by-name parameter

def myAssert(predicate: => Boolean) = //leave out '()'
    if(!predicate) throw new AssertionError //leave out '()'

then, you can use myAssert as above

myAssert(5 > 3)

Notes: A by-name type, in which the empty parameter list, (), is left out, is only allowed for parameters. There is no such thing as a by-name variable or a by-name field.

Good luck with you.

Upvotes: 3

Related Questions