https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
s

Smallville7123

04/18/2019, 12:18 PM
how do i compare
Number
for example
fun Number.comparisionsGreaterThan(i: Number): Boolean {
    return this < i
}
w

wbertan

04/18/2019, 12:21 PM
I believe because
Number
doesn't implement
Comparable
.
/*
 * Copyright 2010-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * <http://www.apache.org/licenses/LICENSE-2.0>
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kotlin

/**
 * Superclass for all platform classes representing numeric values.
 */
public abstract class Number {
    /**
     * Returns the value of this number as a [Double], which may involve rounding.
     */
    public abstract fun toDouble(): Double

    /**
     * Returns the value of this number as a [Float], which may involve rounding.
     */
    public abstract fun toFloat(): Float

    /**
     * Returns the value of this number as a [Long], which may involve rounding or truncation.
     */
    public abstract fun toLong(): Long

    /**
     * Returns the value of this number as an [Int], which may involve rounding or truncation.
     */
    public abstract fun toInt(): Int

    /**
     * Returns the [Char] with the numeric value equal to this number, truncated to 16 bits if appropriate.
     */
    public abstract fun toChar(): Char

    /**
     * Returns the value of this number as a [Short], which may involve rounding or truncation.
     */
    public abstract fun toShort(): Short

    /**
     * Returns the value of this number as a [Byte], which may involve rounding or truncation.
     */
    public abstract fun toByte(): Byte
}
public class Int private constructor() : Number(), Comparable<Int> { ... }
s

Stephan Schroeder

04/18/2019, 12:56 PM
you can cast to double!
fun Number.comparisionsGreaterThan(i: Number) = this.toDouble() < i.toDouble()
s

Smallville7123

04/18/2019, 1:26 PM
@Stephan Schroeder would that work for all classes implimenting
Number
in such that all information is preserved and nothing gets truncated as a result?
r

Ruckus

04/18/2019, 2:18 PM
No, of course not. That's why
Number
isn't comparable, why Kotlin doesn't do automatic number conversions, and why different number types exist in the first place.
For a simple example:
val x = 21412415121234567L
val y = x + 1
println(x.toDouble() < y.toDouble())

> false
s

Smallville7123

04/18/2019, 2:27 PM
;-;
s

Stephan Schroeder

04/18/2019, 2:39 PM
that's when you run into NAN (not a number, which is a double). toDouble is defined on Number, so every instance of Number will be able to execute this code. At the same time Double is the type with the highest resolution, so this should work for all current primitive types (signed/unsigned byte, short, int, long, float and double). Of course if you have to deal with e.g. bigger than Double.maxValue BigIntegers than this will stop working. But this is close to the best you can do (you could verify the type of your numbers at runtime and cast accordingly, but this would introduce an overhead that would be be simply unneccessary for all "normal cases). You have to decide if this is good enough. If your application requires t.ex. BigIntegers, maybe compare them directly instead of relying on this method.
ah, ok. I though it would work for long as well. Looks like long.maxValue > double.maxValue.
r

Ruckus

04/18/2019, 2:42 PM
Double is the type with the highest resolution
That's simply not true. In my example, leaving the values as
Long
would return true.
s

Stephan Schroeder

04/18/2019, 2:42 PM
you're correct, my mistake
r

Ruckus

04/18/2019, 2:46 PM
Many languages have "automatic widening" that will do this for you, which is why so many people have this idea that doubles can just hold more values. It's unfortunate and technically wrong. Some languages take the difference even further than Kotlin. For example, Rust has a concept of "partial comparability" that floating point values use, since
NaN
isn't actually comparable to anything.
s

Stephan Schroeder

04/18/2019, 2:47 PM
if you're willing to take the performance overhead, convert everything to BigDecimal 😎 (i wouldn't, maybe there is a reason why Number isn't Comparable 😉)
🤪 1
😱 1
k

karelpeeters

04/18/2019, 3:03 PM
That's still not enough, other people could have written even bigger or more precise
Number
implementations.
You rightfully can't do anything with a
Number
, I'd try to avoid using it at all.
s

Smallville7123

04/18/2019, 3:21 PM
ok
so id need 8 (how many functions i have) * (how every many primative number types plus 1 for BigIntegers) function declarations total
if i want to avoid
Number
k

karelpeeters

04/18/2019, 3:24 PM
Yes, this is a common frustration 😒imple_smile:
s

Smallville7123

04/18/2019, 3:24 PM
rip
can i alias
<
k

karelpeeters

04/18/2019, 3:24 PM
The stdlib solves this problem by actually generating the code.
No, it maps to
.compareTo
.
s

Smallville7123

04/18/2019, 3:25 PM
and
<=
>
>=
==
!=
That said, you could just write it like this:
fun <T: Comparable<T>> T.comparisionsGreaterThan(other: T): Boolean {
    return this < other
}
s

Smallville7123

04/18/2019, 3:26 PM
like alias
isNotEqualTo
to
!=
which resolves to
.compareTo
k

karelpeeters

04/18/2019, 3:27 PM
You can do that, see the code I wrote.
s

Smallville7123

04/18/2019, 3:27 PM
but arent `String`'s comparable too?
k

karelpeeters

04/18/2019, 3:27 PM
Yes, this will include a bunch of other stuff.
s

Smallville7123

04/18/2019, 3:27 PM
in which "a" < "b" would not make sence
k

karelpeeters

04/18/2019, 3:28 PM
It does make sense, you can do that in Kotin if you want.
s

Smallville7123

04/18/2019, 3:28 PM
what happens o.o
k

karelpeeters

04/18/2019, 3:28 PM
You can artificially restrict it to
Number
, but that's kind of shady:
fun <T> T.comparisionsGreaterThan(other: T): Boolean where T : Comparable<T>, T: Number {
    return this < other
}
s

Smallville7123

04/18/2019, 3:30 PM
imma just leave it as comparable...
so this?
infix fun <T: Comparable<T>> T.isGreaterThan(i: T) = this > i

infix fun <T: Comparable<T>> T.isGreaterThanOrEqualTo(i: T) = this >= i

infix fun <T: Comparable<T>> T.isLessThan(i: T) = this < i

infix fun <T: Comparable<T>> T.isLessThanOrEqualTo(i: T) = this <= i

infix fun <T: Comparable<T>> T.isEqualTo(i: T) = this == i

infix fun <T: Comparable<T>> T.isNotEqualTo(i: T) = this != i
as even though is intended to be used with numbers, it apparently also can be used with other types that have Comparable so ill just leave it to the user to decide lol
k

karelpeeters

04/18/2019, 3:33 PM
Sure, but why does this code exist? It just increases the verbosity.
Also, switch to expression bodies: drop the
: Boolean
,
{}
, and
return
.
That was fast 😛
s

Smallville7123

04/18/2019, 3:35 PM
XD
k

karelpeeters

04/18/2019, 3:36 PM
Still curious what you're trying to achieve with this.
s

Smallville7123

04/18/2019, 3:36 PM
cus remembering what < and > means is confusing lol
k

karelpeeters

04/18/2019, 3:36 PM
??? You never did maths?
s

Smallville7123

04/18/2019, 3:37 PM
no? o.o
i rarely use them lol
k

karelpeeters

04/18/2019, 3:37 PM
Like in school, did you never had a math class or anything like that?
s

Smallville7123

04/18/2019, 3:38 PM
i did, but that was years ago lol
k

karelpeeters

04/18/2019, 3:38 PM
Try to imagine the
>
thing wanting to "eat" as much as possible, so
2 < 5
because it wants to eat the
5
.
😆 1
r

Ruckus

04/18/2019, 3:39 PM
@karelpeeters I've never heard that one before. That's pretty good.
k

karelpeeters

04/18/2019, 3:40 PM
Credit to my first-grade teacher who had a crocodile puppet that ate lego bricks!
👍 1
s

Smallville7123

04/18/2019, 3:41 PM
nu
r

Ruckus

04/18/2019, 3:45 PM
I only learned the big number goes on the big side and the little number goes on the little side.
k

karelpeeters

04/18/2019, 3:46 PM
Boooring! 😛
r

Ruckus

04/18/2019, 3:46 PM
Agreed