0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

(1) def compare[T](num1: T, num2: T): Boolean ... is not a good example, unless you want to compare hash codes since you don't know anything about type T. Containers are better examples with no type bounds. (2) In the first def myAssert ... you are supposed to write if(!predicate()), functions require explicit parentheses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.