title: How to implement a validating constructor in Kotlin?
body: <p>I'm implementing vars in Kotlin that could receive out-of-bounds input from certain of their users.  I'd like to be able to optionally call (only on input from these untrusted users) a validating constructor that can return null, and then use the Elvis operator to specify defaults in the case of invalid input, as in:  <code>var myFoo = Foo.fromInt(i) ?: 1</code>.  I'm currently using a companion object method to validate the input:</p>
  
  <pre><code>open class Foo(val x:Int) {   // relies on valid x in 1..3
    companion object {
      fun fromInt(x: Int): Foo? = if (x in 1..3) Foo(x) else null
    }
  }
  class Bar(x:Int) : Foo(x)
  
  fun main(args:Array&lt;String&gt;) {
    println(Foo.fromInt(2))    // Foo(2)
    println(Foo.fromInt(20))   // null
    // println(Bar.fromInt(2))
    // would like Bar(2) but as expected, companion isn't inherited
  }
  </code></pre>
  
  <p>When I subclass <code>Foo</code>, I know I have to recreate the companion object.  I've tried inheriting the companion from an abstract class; however, the call to <code>Foo(x)</code> still points to <code>Foo</code> and not <code>Bar</code>, unless I override <code>fromInt</code> in each subclass' companion.  Is there a better or more Kotlin-idomatic way to deal with this kind of pattern of a validating constructor that can return <code>null</code> rather than creating the requested object?</p>