generics - What compile-time type must I assign to receieve a return value of java.util.Map<TextAttribute, ?> -


i'd make font derived out of font. here's trying do:

val font : font = this.label.getfont(); val attributes : map<textattribute, any> = font.getattributes(); attributes.put(textattribute.underline, textattribute.underline_on); this.label.setfont(font.derivefont(attributes)); 

however, kotlin compiler complains @ line:

val attributes : map<textattribute, any> = font.getattributes(); 

with message:

 type mismatch: inferred type  (mutable)map<textattribute!, *>!  map<textattribute, any> expected 

per limited understanding of generics in java, understand font.getattributes() returns java.util.map<textattribute, ?>; latter type parameter means when create bounded / closed generic type out of map, please specify second type parameter, extends java.lang.object.

so, when tried following line @ first:

val attributes : java.util.map<textattribute, object> = font.getattributes(); 

the kotlin compiler said:

this class shouldn't used in kotlin. use kotlin.collections.map or kotlin.collections.mutablemap instead.

and said:

 type mismatch: inferred type   (mutablemap<textattribute!, *>..kotlin.collections.map<textattribute!, *>?)   java.util.map<textattribute, object> expected 

i have no idea ! symbol means , wildcard asterisk symbol means. saying?

the first problem getattributes method returns map can hold nulls whereas map<textattribute, any> declares values must not null. second problem map interface in kotlin not allow mutation.

to resolve problems change code e.g.:

val attributes : map<textattribute, *> = font.getattributes(); val updatedattributes = attributes.plus(textattribute.underline textattribute.underline_on) 

or more concise:

val updatedattributes = font.attributes.plus(textattribute.underline textattribute.underline_on) 

finally since kotlin has handy extension methods whole font mangling can turned into:

label.font = label.font.run {      derivefont(attributes.plus(textattribute.underline textattribute.underline_on))  } 

Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -