Generate equals() method for a message.
(self, message: Message)
| 2025 | ] |
| 2026 | |
| 2027 | def generate_equals_method(self, message: Message) -> List[str]: |
| 2028 | """Generate equals() method for a message.""" |
| 2029 | lines = [] |
| 2030 | lines.append("@Override") |
| 2031 | lines.append("public boolean equals(Object o) {") |
| 2032 | lines.append(" if (this == o) return true;") |
| 2033 | lines.append(" if (o == null || getClass() != o.getClass()) return false;") |
| 2034 | lines.append(f" {message.name} that = ({message.name}) o;") |
| 2035 | |
| 2036 | if not message.fields: |
| 2037 | lines.append(" return true;") |
| 2038 | else: |
| 2039 | comparisons = [] |
| 2040 | for field in message.fields: |
| 2041 | field_name = self.to_camel_case(field.name) |
| 2042 | if self.is_primitive_array_field(field): |
| 2043 | comparisons.append( |
| 2044 | f"Arrays.equals({field_name}, that.{field_name})" |
| 2045 | ) |
| 2046 | elif self.field_type_contains_array(field.field_type): |
| 2047 | comparisons.append( |
| 2048 | f"deepValueEquals({field_name}, that.{field_name})" |
| 2049 | ) |
| 2050 | elif isinstance(field.field_type, PrimitiveType): |
| 2051 | kind = field.field_type.kind |
| 2052 | if kind in (PrimitiveKind.FLOAT32,): |
| 2053 | comparisons.append( |
| 2054 | f"Float.compare({field_name}, that.{field_name}) == 0" |
| 2055 | ) |
| 2056 | elif kind in (PrimitiveKind.FLOAT64,): |
| 2057 | comparisons.append( |
| 2058 | f"Double.compare({field_name}, that.{field_name}) == 0" |
| 2059 | ) |
| 2060 | elif ( |
| 2061 | kind |
| 2062 | in ( |
| 2063 | PrimitiveKind.BOOL, |
| 2064 | PrimitiveKind.INT8, |
| 2065 | PrimitiveKind.INT16, |
| 2066 | PrimitiveKind.INT32, |
| 2067 | PrimitiveKind.INT64, |
| 2068 | ) |
| 2069 | and not field.optional |
| 2070 | ): |
| 2071 | comparisons.append(f"{field_name} == that.{field_name}") |
| 2072 | else: |
| 2073 | comparisons.append( |
| 2074 | f"Objects.equals({field_name}, that.{field_name})" |
| 2075 | ) |
| 2076 | else: |
| 2077 | comparisons.append( |
| 2078 | f"Objects.equals({field_name}, that.{field_name})" |
| 2079 | ) |
| 2080 | |
| 2081 | if len(comparisons) == 1: |
| 2082 | lines.append(f" return {comparisons[0]};") |
| 2083 | else: |
| 2084 | lines.append(f" return {comparisons[0]}") |
no test coverage detected