You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (JIRA)" <ji...@apache.org> on 2019/01/15 21:31:00 UTC

[jira] [Commented] (GROOVY-8957) String with length 1, if assigned to int variable, assigns the ascii value. String with more than 1 length throws GroovyCastException

    [ https://issues.apache.org/jira/browse/GROOVY-8957?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16743411#comment-16743411 ] 

Paul King commented on GROOVY-8957:
-----------------------------------

This all looks like expected behavior to me. Since Groovy Strings took over Java's single quotes for characters, Groovy makes special provision for characters (always size 1) to also be in single quotes. The type can be char or int. Using 'as int' calls .toInteger() on a string which can be of length greater than 1. So, you need 'as int' to avoid the cast exception.

> String with length 1, if assigned to int variable, assigns the ascii value. String with more than 1 length throws GroovyCastException
> -------------------------------------------------------------------------------------------------------------------------------------
>
>                 Key: GROOVY-8957
>                 URL: https://issues.apache.org/jira/browse/GROOVY-8957
>             Project: Groovy
>          Issue Type: Bug
>          Components: groovy-jdk
>            Reporter: Adithyan K
>            Priority: Major
>
> String with length 1, if assigned to int variable, assigns the ascii value. String with more than 1 length throws GroovyCastException
> {code}
> /*line 1  : case-1 */ char    c1 = '1'
> /*line 2  : case-1 */ int     n1 = c1
> /*line 3  : case-1 */ println "n1 = $n1" //prints ascii value of 1 :'n1 = 49'
> /*line 4  : case-2 */ String  s2 = '1'
> /*line 5  : case-2 */ int     n21 = s2
> /*line 6  : case-2 */ int     n22 = s2 as int
> /*line 7  : case-2 */ println "n21 = $n21" //prints 'n21 = 49'
> /*line 8  : case-2 */ println "n22 = $n22" //prints 'n22 = 1'
> /*line 9  : case-3 */ String  s3 = '10'
> /*line 10 : case-3 */ int     n3 = s3 //Throwing Cast Exception
> /*line 11 : case-3 */ println n3
> {code}
> Case-1
> Line 3 prints `49`. It is ok as `char` is assgined to integer in line 2
> Case-2
>  Line 7 prints  `n21` eventhough String is assgined in line 5... Is it right?
> Line 6 : `n22` is assigned 1 as I have written `s2 as int`. This is ok
> Case-3
>  Line 10 : Throwing GroovyCastException. This is ok.
> The difference between Line-5 and Line-10 is the difference in String length. Both are Strings. The former is of length 1 and the latter is of length 2.
> So, String with length 1, if assigned to int variable, assigns the ascii value. String with more than 1 length throws GroovyCastException This looks some what different...
> Is it the acceptable behavior
>  



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)