Search code examples
scalahibernate-validator

Creating a Hibernate Method Validator in Scala


I'm trying to convert this Java code into Scala, and I am failing:

Java (which compiles without error):

Validation.byProvider(HibernateValidator.class).configure().
    buildValidatorFactory().getValidator().unwrap(MethodValidator.class);

Scala:

Validation.byProvider(classOf[HibernateValidator]).configure.
    buildValidatorFactory.getValidator.unwrap( classOf[MethodValidator] )

Scala error:

inferred type arguments [Nothing,org.hibernate.validator.HibernateValidator] do 
  not conform to method byProvider's type parameter bounds [T <: 
  javax.validation.Configuration[T],U <: 
  javax.validation.spi.ValidationProvider[T]]

What am I doing wrong?

I am using Scala 2.10 and have JBoss 7.1.0 on the classpath.


Solution

  • It looks like scala is having a little trouble infering some types. This should work:

    Validation.byProvider[HibernateValidatorConfiguration, HibernateValidator](classOf[HibernateValidator])
       .configure.buildValidatorFactory.getValidator.unwrap(classOf[MethodValidator])
    

    If you look at the source of byProvider you'll find this:

    public static <T extends javax.validation.Configuration<T>, 
        U extends javax.validation.spi.ValidationProvider<T>>  
        javax.validation.bootstrap.ProviderSpecificBootstrap<T> 
        byProvider(java.lang.Class<U> providerType)
    

    So scala should pick up that HibernateValidator has HibernateValidatorConfiguration implemented, but it doesn't.