Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1521,13 +1521,20 @@ private boolean typeCheckMultipleAssignmentPositional(final Expression leftExpre
}

for (int i = 0, n = tupleExpressions.size(); i < n; i += 1) {
Expression tupleExpression = tupleExpressions.get(i);
ClassNode valueType = getType(valueExpressions.get(i));
ClassNode targetType = getType(tupleExpressions.get(i));
ClassNode targetType = getType(tupleExpression);
if (!isAssignableTo(valueType, targetType)) {
addStaticTypeError("Cannot assign value of type " + prettyPrintType(valueType) + " to variable of type " + prettyPrintType(targetType), rightExpression);
return false;
}
storeType(tupleExpressions.get(i), valueType);
// GROOVY-12228: check for implicit conversion like "String a = 123" or "Long b = 1";
// as for single assignment, the target then holds its declared type, not the value type
ClassNode originType = getOriginalDeclarationType(tupleExpression);
if (!implementsInterfaceOrIsSubclassOf(wrapTypeIfNecessary(valueType), wrapTypeIfNecessary(originType))) {
valueType = originType;
}
storeType(tupleExpression, valueType);
}

return true;
Expand Down
40 changes: 40 additions & 0 deletions src/test/groovy/groovy/transform/stc/STCAssignmentTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -1467,6 +1467,46 @@ class STCAssignmentTest extends StaticTypeCheckingTestCase {
'''
}

// GROOVY-12228
@Test
void testMultiAssignRetainsDeclaredType1() {
assertScript '''
def m() {
String a, b
(a, b) = ["x${1}", "y${2}"]
assert a instanceof String
assert a.class === String && b.class === String
assert a == 'x1' && b == 'y2'
}
m()
'''
}

// GROOVY-12228
@Test
void testMultiAssignRetainsDeclaredType2() {
assertScript '''
def m() {
def (String a, String b) = ["x${1}", "y${2}"]
assert a.class === String && b.class === String
}
m()
'''
}

// GROOVY-12228
@Test
void testMultiAssignRetainsDeclaredType3() {
assertScript '''
def m() {
Long a, b
(a, b) = [1, 2]
assert a.class === Long && b.class === Long
}
m()
'''
}

// GROOVY-10943
@Test
void testMultiAssignUnderscorePlaceholder1() {
Expand Down
Loading