- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why can't 'kotlin.Result' be used as a return type?
Result is a Serializable class in Kotlin. The function definition looks like this −
class Result<out T> : Serializable
This class has two properties − "isFailure" and "isSuccess".
As per the documentation, Result<T> cannot be used as a direct return type of Kotlin function. However, in this article, we will see how we can use this Result in our Kotlin programs.
// ERROR: 'kotlin.Result' cannot be used as a return type fun findUserByName(name: String): Result<User> fun foo(): Result<List<Int>> // ERROR fun foo(): Result<Int>? // ERROR var foo: Result<Int> // ERROR
Example – Kotlin.Result
sealed class myInterFace<out Success, out Failure> data class Success<out Success>(val value: Success) : myInterFace<Success, Nothing>() data class Failure<out Failure>(val reason: Failure) : myInterFace<Nothing, Failure>() fun myMethod(string : String) : myInterFace<String, Exception> { return if (string.isEmpty()) { Failure(Exception("Error in the process")) } else { Success(string) } } fun main(args : Array<String>) { when(val result = myMethod("")) { is Success -> println(result.value) is Failure -> println(result.reason) } }
Output
On execution, it will produce the following output −
java.lang.Exception: Error in the process
- Related Articles
- Why can't Java generics be used for static methods?
- Why a virus can't be killed using antibiotics?
- Why can a pace or a footstep not be used as a standard unit of length?
- Can MongoDB return result of increment?
- How can MySQL FIND_IN_SET() function be used to get the particular record(s) from the table as a result set?
- Why can't a Java class be both abstract and final?
- Why can't static method be abstract in Java?
- Return the cumulative product treating NaNs as one but change the type of result in Python
- Which type of mirror could be used as a dentist's mirror?
- Can we return Result sets in JDBC?
- What type of mirror should be used:(a) as a shaving mirror?(b) as a shop security mirror?
- Why petrol cannot be used as a fuel in stoves at homes?
- How can Tensorflow be used with Estimators to return a two element tuple?
- Why cannabis used as a medicine?
- MySQL query to return a string as a result of IF statement?

Advertisements