However, I still cannot get that example to compil...
# announcements
n
However, I still cannot get that example to compile when converted to Kotlin syntax. Seems to be a limitation of either the Kotlin type inference algorithm, or (more likely) my ability to bend it to my will.
j
Sovled this problem. thank you! https://pl.kotl.in/rJIgyjMUE
metal 1
n
Ah yes! Extension functions. Whenever I have a problem wrangling generic type parameters of methods, the problem goes away when I replace methods with functions.
I must remember that!
r
I'm not sure it's ok
Copy code
val v = Option("test")
println(v.getOrElse { 0 })
it should not work this way
n
What’s wrong with that?
I noticed that I solved this very problem with the same solution: https://github.com/npryce/result4k/blob/master/src/main/kotlin/com/natpryce/result.kt#L69
r
Option<String> should not return Int
n
Option("test").getOrElse{0}
has type
Any
, and println can be passed an Any
That is… Any is a supertype of String, 0 is an Int, which is a subtype of Any, so B gets unified to Any
p
@Robert Jaros right - with extension function in this case we cannot achive that level of 'type safety'. As i know, there is plan to add lower bound check in 'where' clause...
r
I was convinced that Scala's type system is better than Kotlin, but Scala's Option implementation isn't better when it comes to type safety 😉
Copy code
scala> Option[java.util.Date](new java.util.Date()).getOrElse(0).getTime()
<console>:8: error: value getTime is not a member of Any
p
Without lower bounds in generic parameters in 'where' it is impossible for now to make perfect solution. Waiting for language improvements...
p
But what is the problem? You want that return type is super type of type
T
.
Any
is super type of
String
, so function can return value of type
Any
and value
0
passes this condition. I suppose that you agree that this code should be allowed:
Copy code
Option("test").getOrElse { 0 as Any }
and compiler is just smart enough to infer type which will pass condition even without explicit cast.
👍 1
p
Generics are invented to avoid this :)