Search code examples
mojolang

How to define overloaded function in MOJO language?


The code below fails.

  
fn greet(n: Bool) -> String:
    return "Hello, 2!"
  
fn greet(name: String) -> String:
    return "Hello, " + name + "!"

fn main():
    print(greet("hi"))
    print(greet(False))

MOJO online Playground


Solution

  • First, welcome to Mojo🔥!

    You are really close. I see two issues:

    1. Your Bool version of greet() is not using the arg, which will cause the compiler to be fussy. Therefore, in the example below, I added an evaluation of n just to quickly skip past this issue.
    2. Calling greet("hi") is passing a StringLiteral and not a String. By using str() around the "hi" you get that converted to a String.
    # file __temp/overload.mojo
    
    fn greet(n: Bool) -> String:
        if n:
            return "Hello! 'n' was True!"
        else:
            return "Heya! 'n' was False!"
    
    fn greet(name: String) -> String:
        return "Hello, " + name + "!"
    
    fn main():
        print(greet(str("world")))
        print(greet(False))
    

    Result:

    Hello, world!
    Heya! 'n' was False!
    

    Also, instead of worrying about String vs StringLiteral, you could use the Stringable trait. That identifies any object (including your own custom concoctions) that provide a __str__() -> String method.

    # updated file contents
    
    fn greet(n: Bool) -> String:
        if n:
            return "Hello! 'n' was True!"
        else:
            return "Heya! 'n' was False!"
    
    fn greet[T: Stringable](name: T) -> String:
        return "Hello, " + str(name) + "!"
    
    @value
    struct MyStruct(Stringable):
        var some_data: Int
        var more_data: Bool
    
        fn __str__(self) -> String:
            return "Call me Bob, even though I'm really this: 'MyStruct(" + str(self.some_data) + ", " + str(self.more_data) + ")'"
    
    
    fn main():
        print(greet("world"))
        print(greet(False))
    
        var x = MyStruct(5, True)
        print(greet(x))
    

    Result:

    Hello, world!
    Heya! 'n' was False!
    Hello, Call me Bob, even though I'm really this: 'MyStruct(5, True)'!
    

    Read more about Stringable here: https://docs.modular.com/mojo/manual/traits#the-intable-and-stringable-traits

    Of note: this answer is current as of Mojo nightly, version 2024.5.1515 (077049dc). The language is still evolving; subtle changes could occur between this post and any future reader.