https://kotlinlang.org logo
Title
u

Udit003

07/22/2018, 11:20 AM
package com.classLesson sealed class Person { // why compiler is complaining here class Men : Person() class Women : Person() abstract fun Sexuality() : String } class Men : Person() { override fun Sexuality(): String { return "M" } } class Women : Person() { override fun Sexuality(): String { return "F" } } // compiler should complain for this class Animal : Person() { override fun Sexuality(): String { return "shouldn't be allowed" } } fun main(args: Array<String>) { var a: Person = Animal() when (a) { is Men -> println("Men") is Animal -> println("Animal") } } @
a

Andreas Sinz

07/22/2018, 11:30 AM
Please surround your code with 3 backticks (`)
👍 3
1: Compiler complains about
Men
, because you have an
abstract fun Sexuality()
that isn't implemented inside the class, 2: Why should the compiler complain about
Animal
?
u

Udit003

07/22/2018, 11:43 AM
Compiler should complain about Animal because I am limiting my possible derived classes to be Men , Women only
That's the whole point of sealed class as per my understanding
a

Andreas Sinz

07/22/2018, 11:44 AM
Kotlin allows you to define subclasses either inside the sealed class or in the same file
You cannot inherit from
Person
outside of the file where it is declared
u

Udit003

07/22/2018, 11:45 AM
Yeah so , I am defining my subclasses in the same file
a

Andreas Sinz

07/22/2018, 11:47 AM
And by the way, you are actually declaring the
Men
-class twice, first inside
Person
and a second time beneath it
thats not needed, you can either declare the class inside or beneath it
u

Udit003

07/22/2018, 11:57 AM
So , you mean all the subclasses defined for a sealed abstract class inside the same file are valid . But they cannot be defined outside the file. Hence it does not Matter if I define my subclasses as "nested" inside the sealed class or as a top level class in the same file.
a

Andreas Sinz

07/22/2018, 12:04 PM
exactly
That way the compiler can guarantee, that
when
-expressions are always exhaustive
u

Udit003

07/22/2018, 1:36 PM
Thank you so much , understood sealed classes , seems really useful and powerful
👍 5