https://kotlinlang.org logo
a

Alex

01/06/2021, 1:30 PM
Copy code
registry.addConverter(
            object : Converter<String, IaaSProvider> {
                override fun convert(source: String): IaaSProvider = IaaSProvider.fromString(source)
            }
        )
Converter is a SAM interface, So technically it would be possible to do something like this:
Copy code
registry.addConverter { source -> IaaSProvider.fromString(source) }
But how would I define generics in this lambda?
j

Javier

01/06/2021, 1:38 PM
they cannot be inferred?
a

Alex

01/06/2021, 2:00 PM
doesn’t seem so
Copy code
void addConverter(Converter<?, ?> converter);
Copy code
@FunctionalInterface
public interface Converter<S, T> {

	/**
	 * Convert the source object of type {@code S} to target type {@code T}.
	 * @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
	 * @return the converted object, which must be an instance of {@code T} (potentially {@code null})
	 * @throws IllegalArgumentException if the source cannot be converted to the desired target type
	 */
	@Nullable
	T convert(S source);

}
j

Javier

01/06/2021, 2:10 PM
it is working for me
you can't add the R and S types to the addConverter funcion?
a

Alex

01/06/2021, 2:17 PM
no, unfortunately
I added an extension function
Copy code
fun <S, T> FormatterRegistry.addConverter(converter: Converter<S, T>) = addConverter(converter)
but now it says it’s shadowed, idk if that’s gonna work
it worked. Thanks 🙂
4 Views