Skip to content

Instantly share code, notes, and snippets.

@zhaohangbo
Last active November 30, 2016 09:46
Show Gist options
  • Save zhaohangbo/b459e6ea701bdc814087325d8a3d43c4 to your computer and use it in GitHub Desktop.
Save zhaohangbo/b459e6ea701bdc814087325d8a3d43c4 to your computer and use it in GitHub Desktop.
Java转成Scala
Java代码转换成Scala,常见的一些转换
转换:
SomeType.class ==> classOf[SomeType]
Class<?> ==> def read[UnknowType](classes: Set[Class[UnknowType]])
https://stackoverflow.com/questions/1135248/scala-equivalent-of-java-java-lang-classt-object
Java代码:
public Swagger read(Set<Class<?>> classes) {
// process SwaggerDefinitions first - so we get tags in desired order
for (Class<?> cls : classes) {
SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);
if (swaggerDefinition != null) {
readSwaggerConfig(cls, swaggerDefinition);
}
}
for (Class<?> cls : classes) {
read(cls);
}
return swagger;
}
Scala代码:
def read[UnknowType](classes: Set[Class[UnknowType]]): Swagger = {
for (cls: Class[UnknowType] <- classes) {
val swaggerDefinition: SwaggerDefinition = cls.getAnnotation(classOf[SwaggerDefinition]) //in Java, SwaggerDefinition.class
if (swaggerDefinition != null) {
readSwaggerConfig(cls, swaggerDefinition)
}
}
for (cls: Class[UnknowType] <- classes) {
read(cls)
}
swagger
}
转换:
使用JavaConverters和JavaConversions
尽量使用JavaConverters,它就是被设计用来代替JavaConversions的
http://docs.scala-lang.org/overviews/collections/conversions-between-java-and-scala-collections.html
https://stackoverflow.com/questions/11679016/java-scala-collection-conversions-scala-2-10
Java代码:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment