Forums

Console.readLine

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Console.readLine

Postby Greg.Bell » Fri Apr 30, 2010 9:35 am

Hi,

I have the following simple code
Code: Select all
"""
Creates a single line "C" style boxed comment
"""
class Program

   def main
   
      title = CobraCore.commandLineArgs[1]
      
      if title == String.empty
         title = Console.readLine
      
      stars = String(c'*',title.length+6)
      spaces = String(c' ',title.length+4)
               
      result = '/[stars]' + Environment.newLine + _
             ' *[spaces]*' + Environment.newLine + _
             ' *  [title.toUpper]  *' + Environment.newLine + _
             ' *[spaces]*' + Environment.newLine + _
             ' [stars]/'
      
      print '[result]'

      Console.readLine


When compiled the compiler spits out the following error:
error: Incompatible types. Cannot assign value of type String? on the right to String on the left.

While I understand this e.g. Console.readLine outputs a nullable string where my 'title' variable is a non-null string. How can I get the input from the console into a variable. I don’t seem to be able to find an example anywhere that documents this.

Thanks

Greg
Greg.Bell
 
Posts: 1

Re: Console.readLine

Postby Charles » Fri Apr 30, 2010 10:23 am

You can typecast an expression to its "non-nil" form with "to !" as in "Console.readLine to !".

Technically this knowledge is present in a How To:
# or typecast to non-nil ("x to !") for those times when you know the value will not be nil
altName = 'Two'
.printValue(altName to !)

at http://cobra-language.com/how-to/UseNilAndNilableTypes/

Although given that you are new to Cobra, I'm not surprised it didn't jump out.

Btw, If we have confidence that .readLine will always return non-nil, then I can enhance the Cobra compiler to assume this. The MSDN docs don't seem to indicate if it could return nil/null (say if stdin was not available). Unfortunately, this is typical of the MSDN docs.

But I have done this for some common methods such a String.replace for which I do have confidence that the method never returns nil/null.
Charles
 
Posts: 2515
Location: Los Angeles, CA


Return to Discussion

Who is online

Users browsing this forum: No registered users and 52 guests