Get startedGet started for free

Type declarations

Another control that we can exercise over our function parameters is the type of these parameters. We can specify a data type for each variable, just as we did in the previous chapter with tuples. If the data type of the argument passed into the function does not match the data type specified when the function was defined, then an error is thrown.

This is another way to control our functions and keep them safe from unwanted exceptions. In the current version of our my_profit function, we could currently pass a string into each argument, but we would get an error when the return statement tries to subtract a string from another string. We can safeguard against this by defining the data type of each parameter.

In the below example, set the data type for each parameter in the function.

Note that if we try to pass a data type that does not match what we have defined, we will get the error:

MethodError: no method matching my_profit(::Int64, ::Int64)

This exercise is part of the course

Intermediate Julia

View Course

Exercise instructions

  • Set the data type for each parameter, where current_price and previous_price should be Float64 values, and fees should only be an Int64 value.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define my_profit with three type-restricted arguments
function my_profit(previous_price____, current_price____, fees____=2)
	return current_price - previous_price - fees
end

# Call my_profit, passing in values of the correct data type
my_profit(100.00, 105.00)
Edit and Run Code