Kotlinのmax()でServlet.service() for servlet [dispatcherServlet] in context with path [] threw exceptionが発生する

# はじめに

kotlinの書籍通りにやっていたらエラーが発生して、どこが原因か探している中で時間がかかったのでまとめます
kotlinでデータのidがもっとも大きいものを見つける際に遭遇したエラーになります

# 問題

以下の書籍をのコードでエラーに遭遇しました

https://www.amazon.co.jp/Kotlin-Web%E3%82%A2%E3%83%97%E3%83%AA%E3%82%B1%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3-%E6%96%B0%E3%81%97%E3%81%84%E3%82%B5%E3%83%BC%E3%83%90%E3%82%B5%E3%82%A4%E3%83%89%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E9%95%B7%E6%BE%A4-%E5%A4%AA%E9%83%8E/dp/4865940669/ref=sr_1_12?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&crid=18CTLYX9QH0UZ&keywords=kotlin&qid=1670939345&sprefix=kotlin%2Caps%2C728&sr=8-12

```kotlin:InMemoryTaskRepository.kt

import org.springframework.stereotype.Repository

@Repository
class InMemoryTaskRepository : TaskRepository {
	private val tasks: MutableList<Task> = mutableListOf(
	)

	private val maxId: Long
		get() = tasks.map(Task::id).max() ?: 0

	override fun create(content: String): Task {
		val id = maxId + 1
		val task = Task(id, content, false)
		tasks += task
		return task
	}
```

`Create`アクションで、`tasks`に新たなタスクを追加しようとすると
`maxId + 1`の部分で`get()`を実行するときにエラーになってしまいます

```
2022-12-13T13:35:37.443Z DEBUG 301 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Failed to complete request: java.util.NoSuchElementException
kotlin  | 2022-12-13T13:35:37.443Z ERROR 301 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.util.NoSuchElementException] with root cause
kotlin  | 
kotlin  | java.util.NoSuchElementException: null
kotlin  |       at kotlin.collections.CollectionsKt___CollectionsKt.maxOrThrow(_Collections.kt:1916) ~[kotlin-stdlib-1.7.21.jar:1.7.21-release-272(1.7.21)]
kotlin  |       at com.example.todolist.InMemoryTaskRepository.getMaxId(InMemoryTaskRepository.kt:10) ~[main/:na]
kotlin  |       at com.example.todolist.InMemoryTaskRepository.create(InMemoryTaskRepository.kt:14) ~[main/:na]
kotlin  |       at com.example.todolist.TaskController.create(TaskController.kt:30) ~[main/:na]
kotlin  |       at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
kotlin  |       at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
kotlin  |       at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
kotlin  |       at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
kotlin  |       at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:906) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731) ~[tomcat-embed-core-10.1.1.jar:6.0]
kotlin  |       at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880) ~[spring-webmvc-6.0.2.jar:6.0.2]
kotlin  |       at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) ~[tomcat-embed-core-10.1.1.jar:6.0]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.2.jar:6.0.2]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.1.jar:10.1.1]
kotlin  |       at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]
kotlin  | 
kotlin  | 2022-12-13T13:35:37.448Z DEBUG 301 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={masked}
kotlin  | 2022-12-13T13:35:37.449Z DEBUG 301 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
kotlin  | 2022-12-13T13:35:37.454Z DEBUG 301 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
kotlin  | 2022-12-13T13:35:37.456Z DEBUG 301 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 500
```

# 解決方法

以下の記事を読んで解決できました

https://www.choge-blog.com/programming/kotlinlistgetmaxvalue/

このパターンで利用できるのは`max`または`maxOrNull`になり、配列に要素がない可能性がある場合は`max()`ではエラーが発生してしまいます

なのでここでは初期の配列が空なので`maxOrNull()`を利用すべきでした

```kotlin:InMemoryTaskRepository.kt

import org.springframework.stereotype.Repository

@Repository
class InMemoryTaskRepository : TaskRepository {
	private val tasks: MutableList<Task> = mutableListOf(
	)

	private val maxId: Long
		get() = tasks.map(Task::id).maxOrNull() ?: 0

	override fun create(content: String): Task {
		val id = maxId + 1
		val task = Task(id, content, false)
		tasks += task
		return task
	}
```

これで最初から配列の状態でもget()が動くようになり、うまく1つ目のタスクが追加できました

# おわりに

慣れてないせいで1つのエラーを解決するのにもとても時間がかかってしまいます
なるべく細かいことでもQiitaにまとめるようにしたいです

# 参考

- [[Kotlin]リスト(List)の最大値を取得するには？](https://www.choge-blog.com/programming/kotlinlistgetmaxvalue/)