Gray
Gray

Reputation: 29

Is there any difference between these two codes?

@Autowired
private StringRedisTemplate stringRedisTemplate;

public void test(String key) {
    // IDEA prompts an error
    Map<String, String> entries1 = stringRedisTemplate.opsForHash().entries(key);
        
    // This is OK.
    HashOperations<String, String, String> opsForHash = stringRedisTemplate.opsForHash();
    Map<String, String> entries = opsForHash.entries(key);  
}

Upvotes: 0

Views: 144

Answers (1)

Roberto
Roberto

Reputation: 9080

The problem Is that the method opsForHash() uses 2 generics, This is the signature:

public <HK, HV> HashOperations<K, HK, HV> opsForHash()

If you want to use a single line, you need to set the generics, just like:

Map<String, String> entries1 = stringRedisTemplate.<String, String>opsForHash().entries(key);

In your code, the second approach works because the compiler finds out the generics from the defined variable on the left side of the = operator.

Upvotes: 4

Related Questions