Page 1 of 1

ToString / toString

PostPosted: Fri Feb 08, 2008 5:04 am
by neuruss
This is what I get when I try to override the method toString:

hello.cobra(47): error: Cannot return String because "toString" is declared to return a void.

What's wrong? Isn't it supposed to return a string?
this is my class:

class Dude
shared
var _l = List<of Dude>()

var _name = ''
var _last = ''
var _age as int

def init(name as String, last as String, age as int)
_name = name.toUpper
_last = last.toUpper
_age = age
_l.add(this)

pro name from var
pro last from var
pro age from var
pro l from var

def toString is override
return '[_name] [_last]'

Re: ToString / toString

PostPosted: Fri Feb 08, 2008 6:05 am
by neuruss
Nevermind, I solved it.
I just had to add "as String" to the method:

def toString as String is override
return '[_name] [_last]'

Re: ToString / toString

PostPosted: Fri Feb 08, 2008 11:20 am
by Charles
If you put your code in (cobra)... (/cobra) tags, but with square brackets instead of parens, then the formatting will be preserved.

So my take away from this is that the error message is poor:

hello.cobra(47): error: Cannot return String because "toString" is declared to return a void.

The word "void" is in the error message but not found in "def toString is override" and there was no warning that you cannot overload by return type.