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
r

robinchew

10/25/2018, 7:25 PM
Hi I'm trying to make the last line work:
fun <T>genattrs(vararg args: T): ArrayList<T> {
    val arrays = ArrayList<T>()
    arrays.addAll(args)
    return arrays
}
val f = ::<Int>genattrs // invalid syntax
s

Shawn

10/25/2018, 7:29 PM
@robinchew try
val f: (Array<out Int>) -> ArrayList<Int> = ::genattrs
💪 1
r

robinchew

10/25/2018, 7:30 PM
Thanks @enleur. Hey again @Shawn, looks like a simillar issue I had before.
s

Shawn

10/25/2018, 7:31 PM
those pesky function types lol
r

robinchew

10/25/2018, 7:34 PM
Hmmmm why Array instead of ArrayList
s

Shawn

10/25/2018, 7:35 PM
that’s what
vararg params: T
is sugar for,
Array<out T>
having a function type like
(vararg Int) -> ...
isn’t supported
not sure if it ever will but ¯\_(ツ)_/¯
r

robinchew

10/25/2018, 7:36 PM
man I would never have figured that
You work at jetbrains designing kotlin or something?
s

Shawn

10/25/2018, 7:37 PM
r

robinchew

10/25/2018, 7:37 PM
I guess I don't read docs
s

Shawn

10/25/2018, 7:37 PM
lol I’m just ribbing you, it’s no biggie
r

robinchew

10/25/2018, 7:38 PM
google, copy, paste programming
s

Shawn

10/25/2018, 7:38 PM
docs aren’t always that helpful until you’ve got a bit of familiarity with the thing documented, anyhow
r

robinchew

10/25/2018, 7:42 PM
Hmm i think im still getting issues
s

Shawn

10/25/2018, 7:42 PM
story of my life lol
r

robinchew

10/25/2018, 7:43 PM
The following:
val attrs: (Array<out Int>) -> ArrayList<Int> = ::genattrs
Is not the same as:
fun attrs(vararg args: Int): ArrayList<Int> {
    val arrays = ArrayList<Int>()
    arrays.addAll(args)
    return arrays
}
I will get the red squiggly underline, when trying to use
attrs(1,2,3)
s

Shawn

10/25/2018, 7:46 PM
well, I’m a little unclear as to what the error is exactly, but I feel like oughta point out that if the function needs to take one type and return another, the signature needs more than one type parameter
so if you’re trying to go from
Virtual...
to
Int
you need a function like
fun <T, R> genAttrs(vararg args: T): ArrayList<R>
r

robinchew

10/25/2018, 7:47 PM
sorry i keep making mistakes
I meant to replace Virtual with Int
s

Shawn

10/25/2018, 7:47 PM
gotcha
I see what you mean
yeah, unfortunately you can’t really have vararg lambda params 😕
I’d bet money there’s a :youtrack: to vote for that concerns it
r

robinchew

10/25/2018, 7:53 PM
Even this has issues:
fun attrs(vararg args: Int): ArrayList<Int> {
    val arrays = ArrayList<Int>()
    arrays.addAll(args)
    return arrays
}
apparently
varargs args: Int
is a
collection<Int>
type, which is not the same as
ArrayList<Int>
.
So I gotta do:
fun attrs(vararg args: Int): ArrayList<Int> {
    val arrays = ArrayList<Int>()
    arrays.addAll(args as ArrayList<Int>)
    return arrays
}
s

Shawn

10/25/2018, 7:54 PM
ah, so, this is another Kotlin gotcha unfortunately
there are optimized arrays for primitive types (or maybe just the primitive numeric types? I oughta read up on that)
so instead of args presenting in the function as
Array<Int>
, it’s
IntArray
, which has a different inheritance hierarchy
r

robinchew

10/25/2018, 7:57 PM
right, so back to the
::genAttrs
problem. I guess this doesn't work?
s

Shawn

10/25/2018, 7:58 PM
if your goal is to take save a reference to a varargs fun such that you can use the reference to call it using varargs, then no, I don’t think it’ll work
r

robinchew

10/25/2018, 8:00 PM
Oh well. Is there an equivalent of
arrayListOf(1,2,3)
but expecting 1 array argument instead, something like
NewArrayList(arrayListOf(1, 2, 3))
s

Shawn

10/25/2018, 8:02 PM
Oh, are you just trying to make a deep copy of an existing arraylist?
or, rather, not a deep copy, but just a copy of an arraylist instead of just another reference
r

robinchew

10/25/2018, 8:03 PM
Actually I basically want to give
arrayListOf
an alternate name, so I can just do
a(1, 2, 3)
instead of
arrayListOf(1,2,3)
s

Shawn

10/25/2018, 8:04 PM
oh
r

robinchew

10/25/2018, 8:04 PM
Doing
a = ::arrayListOf
dont work
s

Shawn

10/25/2018, 8:05 PM
for that you’re just gonna have to define a new function I guess.
fun <T> a(vararg args: T): ArrayList<T> = arrayListOf(*args)
I’d also suggest using a type higher up the chain than
ArrayList
if you can help it
List
if you can do with a read-only interface,
MutableList
if you need those add/remove methods
r

robinchew

10/25/2018, 8:08 PM
I thought
*
wasn't supported, which is like
...
right?
s

Shawn

10/25/2018, 8:08 PM
well
...
means a couple different things depending on the language lol, but
*
is definitely supported as the array spread operator
lets you pass in arrays where you need varargs
r

robinchew

10/25/2018, 8:11 PM
Damn the syntax is weird, a function declaration with
=
instead of
{}
s

Shawn

10/25/2018, 8:12 PM
lol, you don’t need the expression body syntax here, but I like it for one-liners
r

robinchew

10/25/2018, 8:13 PM
foreign, but good to know
s

Shawn

10/25/2018, 8:15 PM
cribbed from 😒cala: iirc
you can even omit the return type when you use expression bodies, but that’s bad juju for public API methods and instances where the return type is ambiguous or unintuitive
r

robinchew

10/25/2018, 8:17 PM
Now what about a short function for a data class?
s

Shawn

10/25/2018, 8:17 PM
going to need to be a bit more specific lol
r

robinchew

10/25/2018, 8:18 PM
Say I got:
data class GlobalState(
    val age: Int = 0,
    val count: Int = 0,
    val selectedIndex: String = "invalid-key")
When instantiating that I just want to do
GS(1, 1, "key")
Just renaming GlobalState is an obvious answer
s

Shawn

10/25/2018, 8:20 PM
I don’t really get your proclivity towards shortening names, but in this case you can just use a
typealias
typealias GS = GlobalState
// elsewhere
val gs = GS(1, 1, "key")
r

robinchew

10/25/2018, 8:21 PM
Just providing choices
If you must know, I'm building an equivalent of this https://mithril.js.org/#dom-elements
s

Shawn

10/25/2018, 8:23 PM
didn’t you say you were coming from a Python background? aren’t you folks all about following the BDFL and there being only one way to do something? 😛
granted, Guido did abdicate a little while back, so I’m not sure where everyone stands on that one lol
r

robinchew

10/25/2018, 8:25 PM
Oh I got a JavaScript background too. I'm out of control.
s

Shawn

10/25/2018, 8:26 PM
wild lol
r

robinchew

10/25/2018, 8:26 PM
m(::LinearLayout,
  attrs(
    size(400, WRAP),
    backgroundColorHex("#009999"),
    elevation(1f),
    margin(50)
  ),
  children(
    m(::TextView,
      arrayListOf(
        onCrup {movingView ->
          value.animation.setView(movingView.parent as LinearLayout)
        },
        size(WRAP, MATCH),
        weight(1f),
        layoutGravity(CENTER_VERTICAL),
        padding(5),
        text("${value.name} ${selectedTop} ${value.checked}"),
        backgroundColorHex("#000066"),
        onTouch {v, motionEvent ->
          val view = v.parent as LinearLayout
s

Shawn

10/25/2018, 10:06 PM
oof
this looks like something much better expressed using a DSL
r

robinchew

10/26/2018, 11:16 AM
No need to learn another language
s

Shawn

10/26/2018, 1:49 PM
no, I mean, like, you can use Kotlin to mimic a DSL
see kotlin/gradle build scripts or #kobalt for example
or even the kotlinx.html example
you could build something that maybe more resembles this
m(LinearLayout) {
  attrs {
    size(400, WRAP)
    backgroundColorHex ="#009999"
    elevation = 1f
    margin = 50
  }

  children {
    +TextView {
      onCrup { movingView ->
          value.animation.setView(movingView.parent as LinearLayout)
      }
      size(WRAP, MATCH)
      weight = 1f
      layoutGravity = CENTER_VERTICAL
      padding = 5
      text = "${value.name} ${selectedTop} ${value.checked}"
      backgroundColorHex = "#000066"
      onTouch { v, motionEvent ->
        view = v.parent as LinearLayout
      }
    }
  }
}
r

robinchew

10/26/2018, 6:39 PM
Thanks for that. At this point though, it's not worth adding more code just to get rid of those commas and brackets.