package hello fun main(args: Array<String>) { println("Hello World!") }
fun main(args: Array<String>) { if (args.size() == 0) { println("Provide a name") return } println("Hello, ${args[0]}!") }
class Greeter(val name: String) { fun greet() { println("Hello, $name") } } fun main(args: Array<String>) { Greeter(args[0]).greet() }
internal class ResourceHolder : AutoCloseable { val resources = ArrayList<AutoCloseable>() fun <T : AutoCloseable> T.autoClose(): T { resources.add(this) return this } override fun close() { resources.reverse() resources.forEach { try { it.close() } catch (e: Throwable) { e.printStackTrace() } } } } inline internal fun <R> using(block: ResourceHolder.() -> R): R { val holder = ResourceHolder() try { return holder.block() } finally { holder.close() } }
fun copy(from: Path, to: Path) { using { val input = Files.newInputStream(from).autoClose() val output = Files.newOutputStream(to).autoClose() input.copyTo(output) } }
ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(System.out::println);
val executor = Executors.newFixedThreadPool(1) executor.execute { println() }
implicit class RichInt(val x: Int) extends AnyVal { def square: Int = x * x } object App { def print(): Unit = { val two = 2 println(s"The square of 2 is ${two.square}") } }
fun Int.richInt(): Int = this * this object App { fun print(): Unit { val two = 2 println("The square of 2 is ${two.richInt()}") } }
buildscript { ext.kotlin_version = '1.0.0-beta-4584' repositories { mavenCentral() maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.0.RELEASE") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version") } } apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'kotlin' jar { baseName = 'test-spring-kotlin-project' version = '0.1.0' } repositories { mavenCentral() maven { url "http://repo.spring.io/snapshot" } maven { url "http://repo.spring.io/milestone" } maven { url "http://10.10.10.67:8081/nexus/content/groups/public" } } dependencies { compile("org.springframework.boot:spring-boot-starter-web:1.3.0.RELEASE") compile("org.springframework:spring-jdbc:4.2.3.RELEASE") compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.6.4") compile("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") }
server.port = 8080
package test.kotlin.spring.project import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.boot.context.web.SpringBootServletInitializer import org.springframework.context.annotation.Bean import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter @SpringBootApplication @EnableAutoConfiguration(exclude = arrayOf(DataSourceAutoConfiguration::class)) open class Application : SpringBootServletInitializer() { @Bean open fun mapperForKotlinTypes(): MappingJackson2HttpMessageConverter { return MappingJackson2HttpMessageConverter().apply { objectMapper = jacksonMapper } } override fun configure(application: SpringApplicationBuilder): SpringApplicationBuilder = application.sources(Application::class.java) companion object { val jacksonMapper = ObjectMapper().registerKotlinModule() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { println("starting application...") SpringApplication.run(Application::class.java, *args) } } }
package test.kotlin.spring.project import org.springframework.http.MediaType import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController data class AckResponse(val status: Boolean, val result: String, val message: String? = null) @RestController class ServiceController { @RequestMapping( path = arrayOf("/request"), method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE)) fun nameRequest( @RequestParam(value = "name") name: String, @RequestParam(value = "surname", required = false) surname: String?): AckResponse { return if (surname == null) AckResponse(status = true, result = "Hi $name", message = "surname is empty") else AckResponse(status = true, result = "Hi $surname,$name") } @RequestMapping( path = arrayOf("/sort_request"), method = arrayOf(RequestMethod.GET), produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE)) fun findMinimum( @RequestParam(value = "values") values: Array<String>): AckResponse { println("values:") values.forEach { println(it) } val minValue = values.apply { sortBy { it.length } } .firstOrNull() ?.split("_") ?.sorted() ?.joinToString(",") ?: "" return AckResponse(status = true, result = minValue) } }
starting application ... . ____ _ __ _ _ / \\ / ___'_ __ _ _ (_) _ __ __ _ \ \ \ \ (() \ ___ | '_ |' _ | | '_ \ / _` | \ \ \ \ \\ / ___) | | _) | | | | | || (_ | |)))) '| ____ | .__ | _ | | _ | _ | | _ \ __, | / / / / ========= | _ | ============== | ___ / = / _ / _ / _ / :: Spring Boot :: (v1.3.0.RELEASE) 2016-01-12 12: 47: 48.242 INFO 88 --- [main] tksproject.Application $ Companion: Starting Application.Companion on Lenovo-PC with PID 88 (D: \ IDA_Projects \ test \ build \ classes \ main started by admin in D: \ IDA_Projects \ test) 2016-01-12 12: 47: 48.247 INFO 88 --- [main] tksproject.Application $ Companion: No profiles are active 2016-01-12 12: 47: 48.413 INFO 88 --- [main] ationConfigEmbeddedWebApplicationContext: Refreshing org.springframework.boot.context.embeddedWebApplicationContext@dbf57b3: startup date [Tue Jan 12 12:47:48 MSK 2016]] root of context hierarchy 2016-01-12 12: 47: 50.522 INFO 88 --- [main] osbfsDefaultListableBeanFactory: Overriding bean for beanNameViewResolver with a different definition: replacing [Root bean: class [null]; scope =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = true; primary = false; factoryBeanName = org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration; factoryMethodName = beanNameViewResolver; initMethodName = null; destroyMethodName = (inferred); [org / springframework / boot / autoconfigure / web / ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration.class]] [Root bean: class [null]; scope =; abstract = false; lazyInit = false; autowireMode = 3; dependencyCheck = 0; autowireCandidate = true; primary = false; factoryBeanName = org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter; factoryMethodName = beanNameViewResolver; initMethodName = null; destroyMethodName = (inferred); defined in class path resource [org / springframework / boot / autoconfigure / web / WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter.class]] 2016-01-12 12: 47: 51.066 INFO 88 --- [main] trationDelegate $ BeanPostProcessorChecker: Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactManthramathrantMathr.AffraTeanMatery.transferamework.transaction.annotation. $$ ede1977c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2016-01-12 12: 47: 51.902 INFO 88 --- [main] sbcetTomcatEmbeddedServletContainer: Tomcat initialized with port (s): 8080 (http) 2016-01-12 12: 47: 51.930 INFO 88 --- [main] o.apache.catalina.core.StandardService: Starting service Tomcat 2016-01-12 12: 47: 51.937 INFO 88 --- [main] org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat / 8.0.28 2016-01-12 12: 47: 52.095 INFO 88 --- [ost-startStop-1] oaccC [Tomcat]. [Localhost]. [/]: Initializing Spring embedded WebApplicationContext 2016-01-12 12: 47: 52.095 INFO 88 --- [ost-startStop-1] osweb.context.ContextLoader: Root WebApplicationContext: initialization completed 3688 ms 2016-01-12 12: 47: 52.546 INFO 88 --- [ost-startStop-1] osbceServletRegistrationBean: Mapping servlet: 'dispatcherServlet' to [/] 2016-01-12 12: 47: 52.556 INFO 88 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'characterEncodingFilter' to: [/ *] 2016-01-12 12: 47: 52.557 INFO 88 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'hiddenHttpMethodFilter' to: [/ *] 2016-01-12 12: 47: 52.559 INFO 88 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'httpPutFormContentFilter' to: [/ *] 2016-01-12 12: 47: 52.559 INFO 88 --- [ost-startStop-1] osbcembedded.FilterRegistrationBean: Mapping filter: 'requestContextFilter' to: [/ *] 2016-01-12 12: 47: 52.985 INFO 88 --- [main] swsmmaRequestMappingHandlerAdapter: Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@dbf57b3: launch date [Tue Jan 12 12 MSK 2016]; root of context hierarchy 2016-01-12 12: 47: 53.089 INFO 88 --- [main] swsmmaRequestMappingHandlerMapping: Mapped "{[/ request], methods = [GET], produces = [application / json; charset = UTF-8]}" " public final test.kotlin.spring.project.AckResponse test.kotlin.spring.project.ServiceController.pullUpdate (java.lang.String, java.lang.String) 2016-01-12 12: 47: 53.094 INFO 88 --- [main] swsmmaRequestMappingHandlerMapping: Mapped "{[/ error]}": java.util.Map <java.lang.String: public org.springframework.http.ResponseEntity <java.util.Map <java.lang.String , java.lang.Object >> org.springframework.boot.autoconfigure.web.BasicErrorController.error (javax.servlet.http.HttpServletRequest) 2016-01-12 12: 47: 53.094 INFO 88 --- [main] swsmmaRequestMappingHandlerMapping: Mapped "{[/ error], produces = [text / html]}" is public org.springframework.web.servlet.ModelAndView org. springframework.boot.autoconfigure.web.BasicErrorController.errorHtml (javax.servlet.http.HttpServletRequest) 2016-01-12 12: 47: 53.138 INFO 88 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/ webjars / **] for class of [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-01-12 12: 47: 53.139 INFO 88 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/ **] for handler type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-01-12 12: 47: 53.195 INFO 88 --- [main] oswshandler.SimpleUrlHandlerMapping: Mapped URL path [/**/favicon.ico] [class org.springframework.web.servlet.resource. ResourceHttpRequestHandler] 2016-01-12 12: 47: 53.512 INFO 88 --- [main] osjeaAnnotationMBeanExporter: Registering beans for JMX exposure on startup 2016-01-12 12: 47: 53.612 INFO 88 --- [main] sbcetTomcatEmbeddedServletContainer: Tomcat started on port (s): 8080 (http) 2016-01-12 12: 47: 53.620 INFO 88 --- [main] tksproject.Application $ Companion: Started Application.Companion in 6.076 seconds (JVM running for 7.177) 2016-01-12 12: 47: 57.874 INFO 88 --- [nio-8080-exec-1] oaccC [Tomcat]. [Localhost]. [/]: Initializing Spring Framework Framework 'dispatcherServlet' 2016-01-12 12: 47: 57.874 INFO 88 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet: FrameworkServlet 'dispatcherServlet': initialization started 2016-01-12 12: 47: 57.897 INFO 88 --- [nio-8080-exec-1] osweb.servlet.DispatcherServlet: FrameworkServlet 'dispatcherServlet': initialization completed in 23 ms
{ status: true, result: "Hi Kris", message: "surname is empty" }
{ status: true, result: "Hi Eagle, Kris" }
{ status: true, result: "1,3,value,virst" }
{ status: true, result: "" }
Source: https://habr.com/ru/post/274997/
All Articles