Overloading arithmetic operators for custom types

Time is not an abstract type, so there is no need to parameterize that.

You are incorrect in thinking the fields are within the constructor’s local scope. They are not.

You can use a short hand notation for binary operators.

import Base: +, -
using Dates: Time, Hour, Minute

struct Clock{S}
    time::Time
    timestring::S
    function Clock(hours::Int64, minutes::Int64)
    
        delta_hours = div(minutes, 60)
        delta_minutes = delta_hours * 60
        hours += delta_hours
        minutes -= delta_minutes
        
        if hours < 0
            hours %= 24
            hours += 24
        end
        
        if minutes < 0
            hours -= 1
            hours %= 24
            minutes += 60
        end
        
        minutes %= 60
        hours %= 24
        time = Time(Hour(hours), Minute(minutes))
        return Clock(time)
    end
    function Clock(time::Time)       
        timestring = Dates.format(time, "HH:MM")
        return new{typeof(timestring)}(time, timestring)
    end
end

c::Clock + m::Minute = Clock(c.time + m)
c::Clock + h::Hour = Clock(c.time + h)
# Addition is commutative
t + c::Clock = c + t

c::Clock - m::Minute = Clock(c.time - m)
c::Clock - h::Hour = Clock(c.time - h)


Base.show(io::IO, ::MIME"text/plain", c::Clock) = print(io, c.timestring)

Here is a demo.

julia> c = Clock(4,5)                                                       
04:05

julia> c + Minute(5)                                                        
04:10  
                                                                                                                                                                                                                                                                                         
julia> c + Minute(5)                                                        
04:10   
                                                                                                                                              
julia> c + Hour(6)                                                          
10:05   
                                                                                                                                             
julia> Hour(7) + c                                                          
11:05      
                                                                                                                                         
julia> Minute(2) + c                                                        
04:07
3 Likes