Hi All, Can somebody explain me how and why the ma...
# announcements
p
Hi All, Can somebody explain me how and why the map function is working with the element instead of the optional?
Why do I need the
it as Snapshot
to make ir work?
c
because if you check, it is the
Optional#map
, not Kotlin
map
, this is because member method always takes preference over extension function with the same name and signature.
Optional
happens to have
map
method with the same signature as Kotlin
map
, so the former is used. As to why you need the cast, check what your
snapshotRepo#save
returns.
p
Thanks. Got the first part. Don’t really get why I need the it as snapshot. If I remove that part, the
orElse(null)
says “found nothing? requires Snapshot”
c
What does your repository return from the
save
method?
p
a Snapshot
c
Are you sure? In that case it should work, does for me.
p
it works but the
orElse(null)
says “found nothing? requires Snapshot” (edited) . It’s a warning
c
can you screenshot quickdoc of the save method?
p
“/** * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the * entity instance completely. * * @param entity must not be {@literal null}. * @return the saved entity will never be {@literal null}. */ <S extends T> S save(S entity);”
Im using a CrudRepository<Snapshot, UUID>
c
Ah, ok... strange let me think about it for a sec.
p
Sure, Don’t worry. I was just curious about why I need the casting
c
you should not need the cast. Something weird is going on here
Ok, I've created a small test project with your code and I don't see any warnings
Copy code
import org.springframework.data.repository.CrudRepository
import java.util.*

fun main() {
	lateinit var snapshotRepo: SnapshotRepo
	fun setSnapshotName(snapshotId: UUID, name: String): Snapshot? {
		val optional: Optional<Snapshot> = snapshotRepo.findById(snapshotId)
		return optional
			.map { it.name = name; snapshotRepo.save(it) }
			.orElse(null)
	}
	setSnapshotName(UUID.randomUUID(), "Test")
}

interface SnapshotRepo : CrudRepository<Snapshot, UUID>

class Snapshot {
	var name: String = ""
}
p
Thanks a lot for your time Alexander. I will check in runtime what happens but yes, I agree that the cast should not eb necessary.