Explicit cast is required to select an appropriate constructor


#1

I'm facing a strange issue when trying to perform simple socket operations. The following code is causing compilation error

fun main(args : Array<String>) {   val socket : Socket = Socket()   val writer : PrintWriter = PrintWriter(socket.getOutputStream()) }

(7, 30) : None of the following functions can be called with the arguments supplied: public constructor PrintWriter(p0: java.io.Writer) defined in java.io.PrintWriter public constructor PrintWriter(p0: java.io.Writer, p1: jet.Boolean) defined in java.io.PrintWriter public constructor PrintWriter(p0: java.io.OutputStream) defined in java.io.PrintWriter public constructor PrintWriter(p0: java.io.OutputStream, p1: jet.Boolean) defined in java.io.PrintWriter public constructor PrintWriter(p0: jet.String) defined in java.io.PrintWriter public constructor PrintWriter(p0: jet.String, p1: jet.String) defined in java.io.PrintWriter public constructor PrintWriter(p0: java.io.File) defined in java.io.PrintWriter public constructor PrintWriter(p0: java.io.File, p1: jet.String) defined in java.io.PrintWriter
which can be solved with an explicit cast
val writer : PrintWriter = PrintWriter(socket.getOutputStream() as OutputStream)
What I can't inderstand is why do we need an explicit cast here? It looks like an argument type can be inferred, but maybe I'm just missing something obvious here.  

#2

This happens because Socket.getOutputStream()'s return type is nullable. It seems that this method never returns null, so we could've had an annotation for that (KT-4322), but for now you're safe asserting that it's non-null:

val writer : PrintWriter = PrintWriter(socket.getOutputStream()!!)

#3

Thanks a lot, that explains much